Any computing problem can be solved by executing a
series of actions in a specific order. A <i>procedure</i> for
solving a problem in terms of<br>
1. the <i>actions</i> to be executed, and<br>
2. the <i>order</i> in which these actions are to be executed<br>
is called an <i>algorithm</i>. The following example
demonstrates that correctly specifying the order in
which the actions are to be executed is important.<br>
<spacer width=16 height=1>Consider the "rise-and-shine algorithm" followed by
one junior executive for getting out of bed and going to
work: (1) Get out of bed, (2) take off pajamas, (3) take a <br>
</page>
<page>
shower, (4) get dressed, (5) eat breakfast, (6) carpool to
work.<br>
<spacer width=16 height=1>This routine gets the executive to work well prepared to
make critical decisions. Suppose, however, that the
same steps are performed in a slightly different order:
(1) Get out of bed, (2) take off pajamas, (3) get dressed,
(4) take a shower, (5) eat breakfast, (6) carpool to work.<br>
<spacer width=16 height=1>In this case, our junior executive shows up for work
soaking wet. Specifying the order in which statements
are to be executed in a computer program is called
<i>program control</i>. In this chapter, we investigate the
program control capabilities of C++.<br>
</page>
<page>
<b>Drag the appropriate term to its matching box so the
resulting sentence defines the term algorithm. </b><br>
A <component type="drag" width=72 height=18 label="procedure" name="procedure"> for solving a problem in terms of the <component type="drag" width=56 height=18 label="actions" name="actions"> to be executed, and the <component type="drag" width=40 height=18 label="order" name="order"> in which these actions are to be executed.<br>
Any computer problem can be solved by a <component type="drop" width=48 height=18 name="procedure"> consisting of a series of <component type="drop" width=48 height=18 name="actions"> executed in <component type="drop" width=48 height=18 name="order">. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
Carefully prepared pseudocode can be easily converted to a C++ progam. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Pseudocode is not executed.">
Pseudocode is one of the slowest executing languages. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.4 Control Structures">
<page>
<font size=18 bold>2.4 Control Structures</font><hr>
Normally, statements in a program are executed one
after the other in the order in which they are written.
This is called <i>sequential execution</i>. Various C++
statements we will soon discuss enable the programmer
to specify that the next statement to be executed may be
other than the next one in sequence. This is called
<i>transfer of control</i>.<br>
<spacer width=16 height=1>During the 1960s, it became clear that the
indiscriminate use of transfers of control was the root of
much difficulty experienced by software development
groups. The finger of blame was pointed at the <b>goto</b> <br>
</page>
<page>
<i>statement</i> that allows the programmer to specify a
transfer of control to one of a very wide range of
possible destinations in a program. The notion of so-
called <i>structured programming</i> became almost
synonymous with "<b>goto</b> <i>elimination</i>."<br>
<spacer width=16 height=1>The research of Bohm and Jacopini (<spacer width=20 height=1>Bohm, C. and G.
Jacopini, "Flow Diagrams, Turing Machines, and
Languages with Only Two Formation Rules,"
Communications of the ACM, Vol. 9, No. 5, May 1966,
pp. 336-371.) had demonstrated that programs could be
written without any <b>goto</b> statements. The challenge of
the era became for programmers to shift their styles to
"<b>goto</b>-less programming." It was not until the 1970s <br>
</page>
<page>
that programmers started taking structured
programming seriously. The results have been
impressive as software development groups have
reported reduced development times, more frequent on-
time delivery of systems, and more frequent within-
budget completion of software projects. The key to
these successes is that structured programs are clearer,
easier to debug and modify, and more likely to be bug-
free in the first place.<br>
<spacer width=16 height=1>Bohm and Jacopini's work demonstrated that all
programs could be written in terms of only three <i>control
structures</i>, namely the <i>sequence structure</i>, the <i>selection
structure</i>, and the <i>repetition structure</i>. The sequence <br>
</page>
<page>
structure is built into C++. Unless directed otherwise,
the computer executes C++ statements one after the
other in the order in which they are written. The
<i>flowchart</i> segment of <a href="^Illustration::c:s0p3"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.1</a> illustrates a typical
sequence structure in which two calculations are
performed in order.<br>
<spacer width=16 height=1>A flowchart is a graphical representation of an
algorithm or of a portion of an algorithm. Flowcharts
are drawn using certain special-purpose symbols such
as rectangles, diamonds, ovals, and small circles; these
symbols are connected by arrows called <i>flowlines</i>. <br>
<spacer width=16 height=1>Like pseudocode, flowcharts are useful for developing
and representing algorithms, although pseudocode is <br>
</page>
<page>
strongly preferred by most programmers. Flowcharts
clearly show how control structures operate; that is all
we use them for in this text. <br>
<spacer width=16 height=1>Consider the flowchart segment for the sequence
structure in <a href="^Illustration::c:s0p3"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.1</a>. We use the <i>rectangle symbol</i>, also
called the <i>action symbol</i>, to indicate any type of action
including a calculation or an input/output operation. The
flowlines in the figure indicate the order in which the
actions are to be performed--first, <b>grade</b> is to be added
to <b>total</b> then <b>1</b> is to be added to <b>counter</b>. C++ allows us
to have as many actions as we want in a sequence
structure. As we will soon see, anywhere a single action <br>
</page>
<page>
may be placed, we may place several actions in
sequence. <br>
<spacer width=16 height=1>When drawing a flowchart that represents a <i>complete</i>
algorithm, an <i>oval symbol</i> containing the word "Begin"
is the first symbol used in the flowchart; an oval symbol
containing the word "End" is the last symbol used.
When drawing only a portion of an algorithm as in <a href="^Illustration::c:s0p3"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig.
2.1</a>, the oval symbols are omitted in favor of using
<i>small circle symbols</i> also called <i>connector symbols</i>. <br>
<spacer width=16 height=1>Perhaps the most important flowcharting symbol is the
<i>diamond symbol</i>, also called the <i>decision symbol</i>, that
indicates a decision is to be made. We will discuss the
diamond symbol in the next section.<br>
</page>
<page>
C++ provides three types of selection structures; we
discuss each of these in this chapter. The <b>if</b> selection
structure either performs (selects) an action if a
condition is <b>true</b> or skips the action if the condition is
<b>false</b>. The <b>if/else</b> selection structure performs an action
if a condition is <b>true</b> and performs a different action if
the condition is <b>false</b>. The <b>switch</b> selection structure
performs one of many different actions depending on
the value of an expression.<br>
<spacer width=16 height=1>The if selection structure is called a <i>single-selection
structure</i> because it selects or ignores a single action.
The <b>if/else</b> selection structure is called a <i>double-
selection structure</i> because it selects between two <br>
</page>
<page>
different actions. The <b>switch</b> selection structure is
called a <i>multiple-selection structure</i> because it selects
the action to perform from many different actions. <br>
<spacer width=16 height=1>C++ provides three types of repetition structures,
namely <b>while</b>, <b>do/while</b> and <b>for</b>. Each of the words <b>if</b>,
<b>else</b>, <b>switch</b>, <b>while</b>, <b>do</b>, and <b>for</b> are C++ <i>keywords</i>.
These words are reserved by the language to implement
various features such as C++'s control structures.
<a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Keywords may not be used as identifiers such as for
variable names. A complete list of C++ keywords is
shown in <a href="^Illustration::c:s0p4"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.2</a>.<br>
Well, that is all there is. C++ has only seven control
structures: sequence, three types of selection and three <br>
</page>
<page>
types of repetition. Each C++ program is formed by
combining as many of each type of control structure as
is appropriate for the algorithm the program
implements. As with the sequence structure of <a href="^Illustration::c:s0p3"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.1</a>,
we will see that each control structure is flowcharted
with two small circle symbols, one at the entry point to
the control structure and one at the exit point. These
<i>single-entry/single-exit control structures</i> make it easy
to build programs--the control structures are attached
to one another by connecting the exit point of one
control structure to the entry point of the next. This is
similar to the way a child stacks building blocks, so we
call this <i>control-structure stacking</i>. We will learn that <br>
</page>
<page>
there is only one other way control structures may be
connected-- <a href="^Engineer::c:s0p0"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>a method called <i>control-structure nesting</i>. <br>
</page>
<page>
<b>Drag the correct term to the box associated with the
prints <i>Passed</i> if the student's grade is greater than or
equal to 60 and prints <i>Failed</i> if the student's grade is
less than 60. In either case, after printing occurs, the
next pseudocode statement in sequence is "performed."
Note that the body of the <b>else</b> is also <a href="^Practice::c:s0p3"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>indented.<br>
<spacer width=16 height=1>Whatever in<a href="^Practice::c:s0p2"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>dentation convention you choose should be
carefully applied throughout your programs. It is
difficult to read programs that do not obey uniform
spacing conventions. <br>
<spacer width=16 height=1>The preceding pseudocode <i>If/else</i> structure may be
written in C++ as<br>
<font size=2><br></font><font size=11><pre>
if ( grade >= 60 ) <p>
cout << "Passed";<p><p>
</pre></font>
</page>
<page>
<font size=2><br></font><font size=11><pre>
else<p>
cout << "Failed";<p>
</pre></font>
The flowchart of <a href="^Illustration::c:s0p6"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.4</a> nicely illustrates the flow of
control in the<b> if/else</b> structure. Once again, note that
(besides small circles and arrows) the only symbols in
the flowchart are rectangles (for actions) and a diamond
(for a decision). We continue to emphasize this action/
decision model of computing. Imagine again a deep bin
containing as many empty double-selection structures
as might be needed to build any C++ program. The
programmer's job is to assemble these selection
structures (by stacking and nesting) with any other
control structures required by the algorithm, and to fill <br>
</page>
<page>
in the empty rectangles and empty diamonds with
actions and decisions appropriate to the algorithm being
implemented. <br>
<spacer width=16 height=1>C++ provides the <i>conditional operator</i> (<b>?:</b>) that is
closely related to the <b>if/else</b> structure. The conditional
operator is C++'s only <i>ternary operator</i>--it takes three
operands. The operands together with the conditional
operator form a <i>conditional expression</i>. The first
operand is a condition, the second operand is the value
for the entire conditional expression if the condition is
<b>true</b>, and the third operand is the value for the entire
conditional expression if the condition is <b>false</b>. For
example, the output statement<br>
</page>
<page>
<font size=2><br></font><font size=11><pre>
cout << ( grade >= 60 ? "Passed" : "Failed" );<p>
</pre></font>
contains a conditional expression that evaluates to the
string "<b>Passed</b>" if the condition <b>grade >= 60</b> is <b>true</b>
and evaluates to the string "<b>Failed</b>" if the condition is
<b>false</b>. Thus, the statement with the conditional operator
performs essentially the same as the preceding <b>if/else</b>
statement. As we will see, the precedence of the
conditional operator is low, so the parentheses in the
preceding expression are required. <br>
The values in a conditional expression can also be
pseudocode statement will print <b>A</b> for exam grades
greater than or equal to 90, <b>B</b> for grades in the range 80
to 89, <b>C</b> for grades in the range 70 to 79, <b>D</b> for grades in
the range 60 to 69, and <b>F</b> for all other grades.<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>If student's grade is greater than or equal to 90<p></i></font></indent><font size=3><br></font>
If <b>grade</b> is greater than or equal to 90, the first four
conditions will be <b>true</b>, but only the <b>cout</b> statement
after the first test will be executed. After that <b>cout</b> is
executed, the <b>else</b>-part of the "outer" <b>if/else</b> statement is <br>
</page>
<page>
skipped. Many C++ programmers prefer to write the
preceding <b>if</b> structure as <br>
<font size=2><br></font><font size=11><pre>
if ( grade >= 90 )<p>
cout << "A";<p>
else if ( grade >= 80 )<p>
cout << "B";<p>
else if ( grade >= 70 )<p>
cout << "C";<p>
else if ( grade >= 60 )<p>
cout << "D";<p>
else<p>
cout << "F";<p>
</pre></font>
<a href="^Perform::c:s0p2"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>Both forms are equivalent. The latter form is popular
because it avoids the deep indentation of the code to the
right. Such indentation often leaves little room on a <br>
</page>
<page>
<a href="^Perform::c:s0p0"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>line, forcing lines to be split and decreasing program
readability.<br>
<spacer width=16 height=1>The <b>if</b> selection structure expects only one statement in
its body. To include several statements in the body of an
<b>if</b>, enclose the statements in braces (<b>{</b> and <b>}</b>). A set of
statements contained within a pair of braces is <a href="^Engineer::c:s0p2"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>called a
<i>compound statement</i>. <br>
<spacer width=16 height=1>The following example includes a compound statement
in the <b>else</b> part of an <b>if/else</b> structure.<br>
<font size=2><br></font><font size=11><pre>
if ( grade >= 60 )<p>
cout << "Passed.\n";<spacer width=20 height=1><p>
else {<p>
cout << "Failed.\n";<p><p>
</pre></font>
</page>
<page>
<font size=2><br></font><font size=11><pre>
cout << "You must take this course again.\n";<p>
}<p>
</pre></font>
In this case, if <b>grade</b> is less than 60, the program
executes both statements in the body of the <b>else</b> and
prints<br>
<font size=2><br></font><font size=11><pre>
Failed.<p>
You must take this course again.<p>
</pre></font>
Notice the braces surrounding the two statements in the
<b>else</b> clause. <a href="^Errors::c:s0p1"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>These braces are important. Without the
braces, the statement<br>
<font size=2><br></font><font size=11><pre>
cout << "You must take this course again.\n";<p>
</pre></font>
</page>
<page>
would be outside the body of the <b>else</b>-part of the <b>if</b>, and
would <a href="^Practice::c:s0p4"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>execute regardless of whether the grade is less
than 60. <br>
<spacer width=16 height=1> <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>A syntax error is caught by the compiler. A <i>logic error</i>
has its effect at execution time. A <i>fatal logic error</i>
causes <a href="^Practice::c:s0p5"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>a program to fail and terminate prematurely. A
<i>nonfatal logic error</i> allows a program to continue <a href="^Engineer::c:s0p3"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>
executing but the program produces incorrect results.<br>
<spacer width=16 height=1>In this section, we introduced the notion of a compound
statement. A compound statement may contain
declarations (as does the body of <b>main</b>, for example). If
so, the compound statement is called a <i>block</i>. The
declarations in a block are commonly placed first in the <br>
</page>
<page>
block before any action statements, but declarations
may be intermixed with action statements. We will
discuss the use of blocks in Chapter 3. The reader
should avoid using blocks (other than as the body of
The compiler associates an else with the closest if unless specified otherwise using braces {}. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.7 The while Repetition Structure">
<page>
<font size=18 bold>2.7 The <b>while</b> Repetition Structure</font><hr>
A <i>repetition structure</i> allows the programmer to specify
that an action is to be repeated while some condition
remains true. The pseudocode statement<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>While there are more items on my shopping list<p>
<spacer width=20 height=1>Purchase next item and cross it off my list</i></font></indent><font size=3><br></font>
describes the repetition that occurs during a shopping
trip. The condition, "there are more items on my
shopping list" may be true or false. If it is true, then the
action, "Purchase next item and cross it off my list" is
performed. This action will be performed repeatedly
while the condition remains <b>true</b>. The statement(s) <br>
</page>
<page>
contained in the <b>while</b> repetition structure constitute the
body of the <b>while</b>. The <b>while</b> structure body may be a
single statement or a compound statement. <a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Eventually,
the condition will become <b>false</b> (when the last item on
the shopping list has been purchased and crossed off the
list). At this point, the repetition terminates, and the
first pseudocode statement after the repetition structure
is executed.<br>
<spacer width=16 height=1>As an example of an <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>actual <b>while</b>, consider a program
segment designed to find the first power of 2 larger than
1000. Suppose the integer variable <b>product</b> has been
initialized to 2. When the following <b>while</b> repetition <br>
</page>
<page>
structure finishes executing, <b>product</b> will contain the
desired answer:<br>
<font size=2><br></font><font size=11><pre>
int product = 2;<p>
while ( product <= 1000 )<p>
product = 2 * product;<p>
</pre></font>
The flowchart of <a href="^Illustration::c:s0p7"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.5</a> illustrates the flow of control
in the <b>while</b> structure that corresponds to the preceding
<b>while</b> structure. Once again, note that (besides small
circles and arrows) the flowchart contains only a
rectangle symbol and a diamond symbol. Imagine a
deep bin of empty <b>while</b> structures that may be stacked
and nested with other control structures to form a
structured implementation of an algorithm's flow of <br>
</page>
<page>
control. The empty rectangles and diamonds are then
filled in with appropriate actions and decisions. The
flowchart clearly shows the repetition. The flowline
emerging from the rectangle wraps back to the decision
that is tested each time through the loop until the
decision becomes <b>false</b>. Then, the while structure
exits and control passes to the next statement in the
program.<br>
When the <b>while</b> structure is entered, the value of
<b>product</b> is 2. The variable <b>product</b> is repeatedly
multiplied by 2, taking on the values 4, 8, 16, 32, 64,
128, 256, 512, and 1024 successively. When <b>product</b>
becomes 1024, the <b>while</b> structure condition, <b>product
</b><br>
</page>
<page>
<b><= 1000</b>, becomes <b>false</b>. This terminates the
repetition--the final value of <b>product</b> is 1024. Program
execution continues with the next statement after the
<b>while</b>.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The while repetition structure has one statement by default.">
The while repetition structure has two statements in the body by default. <br>
Repetition structures allow statements to be repeated until some condition becomes false. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition)">
<page>
<font size=18 bold>2.8 Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)</font><hr>
To illustrate how algorithms are developed, we solve
several variations of a class averaging problem.
Consider the following problem statement:<br>
<font size=6><br></font><indent width=16><font size=14><i>A class of ten students took a quiz. The grades (integers in
the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.</i></font></indent><font size=6><br></font>
The class average is equal to the sum of the grades
divided by the number of students. The algorithm for
solving this problem on a computer must input each of <br>
</page>
<page>
the grades, perform the averaging calculation, and print
the result. <br>
<spacer width=16 height=1>Let us use pseudocode to list the actions to be executed
and specify the order in which these actions should be
executed. We use <i>counter-controlled repetition</i> to input
the grades one at a time. This technique uses a variable
called a<i> counter</i> to control the number of times a set of
statements will execute. In this example, repetition
terminates when the counter exceeds 10. In this section,
we present a pseudocode algorithm ( <a href="^Illustration::c:s0p8"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.6</a>) and the
corresponding program (<a href="^Code::c:s0p0"> </a> <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.7</a>). In the next section,
we show how pseudocode algorithms are developed.
Counter-controlled repetition is often called <i>definite</i> <br>
</page>
<page>
<i>repetition</i> because the number of repetitions is known
before the loop begins executing.<br>
<spacer width=16 height=1>Note the references in the algorithm to a total and a
counter. A <i>total</i> is a variable used to accumulate the
sum of a series of values. A counter is a variable used to
count--in this case, to count the number of grades
entered. Variables used to store totals should normally
be initialized to zero before being used in a program;
otherwise, the sum would include the previous value
stored in the total's memory location. <br>
<spacer width=16 height=1>Counter variables are normally <a href="^Practice::c:s0p6"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>initialized to zero or
one, depending on their use (we will present examples
showing each of these uses). <a href="^Errors::c:s0p7"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>An uninitialized variable <br>
</page>
<page>
contains a "<i>garbage</i>" <i>value</i> (also called an <i>undefined
value</i>)--the value last stored in the memory location
reserved for that <a href="^Practice::c:s0p7"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>variable. <br>
<spacer width=16 height=1>Note that the averaging calculation in the program
produced an integer result. Actually, the sum of the
grades in this example is 817 which when divided by 10
should yield 81.7, i.e., a number with a decimal point.
We will see how to deal with such numbers (called
floating-point numbers) in the next section.<br>
<spacer width=16 height=1>In <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.7</a>, if line 25 <a href="^Errors::c:s0p8"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>used <b>gradeCounter</b> rather than
10 for the calculation, the output for this program
would display a value of 74.<br>
</page>
</section>
<section type=Body name=Default title="2.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition)">
<page>
<font size=18 bold>2.9 Formulating Algorithms with Top-
Down, Stepwise Refinement: Case Study 2
(Sentinel-Controlled Repetition)</font><hr>
Let us generalize the class average problem. Consider
the following problem:<br>
<font size=6><br></font><indent width=16><font size=14><i>Develop a class averaging program that will process an
arbitrary number of grades each time the program is run.</i></font></indent><font size=6><br></font>
In the first class average example, the number of grades
(10) was known in advance. In this example, no
indication is given of how many grades are to be
entered. The program must process an arbitrary number <br>
</page>
<page>
of grades. How can the program determine when to stop
the input of grades? How will it know when to calculate
and print the class average?<br>
<spacer width=16 height=1>One way to solve this problem is to use a special value
called a <i>sentinel value</i> (also called a <i>signal value</i>, a
<i>dummy value</i>, or a <i>flag value</i>) to indicate "end of data
entry." The user types grades in until all legitimate
grades have been entered. The user then types the
sentinel value to indicate that the last grade has been
entered. Sentinel-controlled repetition is often called
<i>indefinite repetition</i> because the number of repetitions
is not known before the loop begins executing.<br>
</page>
<page>
<a href="^Errors::c:s0p10"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>Clearly, the sentinel value must be chosen so that it
cannot be confused with an acceptable input value.
Because grades on a quiz are normally nonnegative
integers, 1 is an acceptable sentinel value for this
problem. Thus, a run of the class average program
might process a stream of inputs such as 95, 96, 75, 74,
89, and 1. The program would then compute and print
the class average for the grades 95, 96, 75, 74, and 89 (
1 is the sentinel value, so it should not enter into the
averaging calculation).<br>
<spacer width=16 height=1>We approach the class average program with a
technique called <i>top-down</i>, <i>stepwise refinement</i>, a
technique that is essential to the development of well-<br>
</page>
<page>
structured programs. We begin with a pseudocode
representation of the <i>top</i>: <br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Determine the class average for the quiz</i></font></indent><font size=3><br></font>
The top is a single statement that conveys the overall
function of the program. As such, the top is, in effect, a
complete representation of a program. Unfortunately,
the top (as in this case) rarely conveys a sufficient
amount of detail from which to write the C++ program.
So we now begin the refinement process. We divide the
top into a series of smaller tasks and list these in the
order in which they need to be performed. This results
<font size=3><br></font><indent width=20><font color=blue size=12><i>Input, sum, and count the quiz grades</i></font></indent><font size=3><br></font>
requires a repetition structure (i.e., a loop) that
successively inputs each grade. Because we do not
know in advance how many grades are to be processed,
we will use sentinel-controlled repetition. The user will
type legitimate grades in one at a time. After the last
legitimate grade is typed, the user will type the sentinel
value. The program will test for the sentinel value after
each grade is input and will terminate the loop when the
sentinel value is entered by the user. The second
refinement of the preceding pseudocode statement is
then<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Input the first grade (possibly the sentinel)<p></i></font></indent><font size=3><br></font>
</page>
<page>
<font size=3><br></font><indent width=20><font color=blue size=12><i>While the user has not as yet entered the sentinel<p>
<spacer width=20 height=1>Add this grade into the running total<p>
<spacer width=20 height=1>Add one to the grade counter<p>
<spacer width=20 height=1>Input the next grade (possibly the sentinel)</i></font></indent><font size=3><br></font>
Notice that in pseudocode, we do not use braces around
the set of statements that form the body of the <b>while</b>
structure. We simply indent the statements under the
<b>while</b> to show that they belong to the <b>while</b>. Again,
pseudocode is only an informal program development
<font size=3><br></font><indent width=20><font color=blue size=12><i>Calculate and print the class average</i></font></indent><font size=3><br></font>
may be refined as follows:<br>
</page>
<page>
<font size=3><br></font><indent width=20><font color=blue size=12><i>If the counter is not equal to zero<p>
<spacer width=20 height=1>Set the average to the total divided by the counter<p>
<spacer width=20 height=1>Print the average<p>
else<p>
<spacer width=20 height=1>Print "No grades were entered"</i></font></indent><font size=3><br></font>
Notice that we are being careful here to test for the
possibility of div<a href="^Errors::c:s0p11"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>ision by zero--a<i> fatal logic error</i> that
if undetected would cause the <a href="^Practice::c:s0p8"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>program to fail (often
called "<i>bombing</i>" or "<i>crashing</i>"). The complete
second refinement of the pseudocode for the class
average problem is shown in <a href="^Illustration::c:s0p9"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.8</a>.<br>
<spacer width=16 height=1>In <a href="^Illustration::c:s0p8"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.6</a> and <a href="^Illustration::c:s0p9"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.8</a>, we include some completely
blank lines in the pseudocode to make the pseudocode <br>
</page>
<page>
more readable. The blank lines separate these programs
into their various phases. <br>
<spacer width=16 height=1>The pseudocode algorithm in <a href="^Illustration::c:s0p9"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.8</a> solves the more
general class averaging problem. This algorithm was
developed after only two levels of refinement.
<a href="^Engineer::c:s0p8"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>Sometimes more levels are necessary.<br>
<spacer width=16 height=1>The C++ program and a sample execution are shown in
<a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.9</a>. Although only integer grades are entered, the
averaging calculation is likely to produce a number
with a decimal point, i.e., a real number. The type <b>int</b>
cannot represent real numbers. The program introduces
the data type <b>float</b> to handle numbers with decimal
points (also called <i>floating-point numbers</i>) and <br>
</page>
<page>
introduces a special operator called a <i>cast operator</i> to
handle the averaging calculation. These features are
explained in detail after the program is presented.<br>
<spacer width=16 height=1>Notice the compound statement in the <b>while</b> loop in
<a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig 2.9</a>. Without the braces, the last three statements in
the body of the loop would fall outside the loop,
causing the computer to interpret this code incorrectly
as follows<br>
<font size=2><br></font><font size=11><pre>
while ( grade != -1 )<p>
total = total + grade;<p>
gradeCounter = gradeCounter + 1;<p>
cout << "Enter grade, -1 to end: ";<p>
cin >> grade;<p>
</pre></font>
</page>
<page>
This would cause an infinite loop if the user does not
input 1 for the first grade. <br>
<spacer width=16 height=1>Notice that the statement<br>
<font size=2><br></font><font size=11><pre>
cin >> grade;<p>
</pre></font>
is preceded by an output statement that <a href="^Practice::c:s0p11"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>prompts the
user for input.<br>
<spacer width=16 height=1>Averages do not <a href="^Practice::c:s0p10"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>always evaluate to integer values.
Often, an average is a value such as 7.2 or -93.5 that
contains a fractional part. These values are referred to
as floating-point numbers and are represented by the
data type <b>float</b>. The variable <b>average</b> is declared to be
of type <b>float</b> to capture the fractional result of our
calculation. However, the result of the calculation <b>total
</b><br>
</page>
<page>
<b>/ counter</b> is an integer because <b>total</b> and <b>counter</b> are
both integer variables. Dividing two integers results in
<i>integer division</i> in which any fractional part of the
calculation is lost (i.e., <i>truncated</i>). Because the
calculation is performed first, the fractional part is lost
before the result is assigned to <b>average</b>. To produce a
floating-point calculation with integer values, we must
create temporary values that are floating-point numbers
for the calculation. C++ provides the <i>unary cast
operator</i> to accomplish this task. The statement<br>
<font size=2><br></font><font size=11><pre>
average = static_cast< float >( total ) / gradeCounter; <p>
</pre></font>
</page>
<page>
includes the cast operator <b>static_cast< float >()</b> which
creates a temporary floating-point copy of its operand
in parentheses--<b>total</b>. Using a cast operator in this
manner is called <i>explicit conversion</i>. The value stored
in <b>total</b> is still an integer. The calculation now consists
of a floating-point value (the temporary <b>float</b> version of
<b>total</b>) divided by the integer <b>counter</b>. <br>
<spacer width=16 height=1>The C++ compiler only knows how to evaluate
expressions in which the data types of the operands are
identical. To ensure that the operands are of the same
type, the compiler performs an operation called
<i>promotion</i> (also called <i>implicit conversion</i>) on selected
operands. For example, in an expression containing the <br>
</page>
<page>
data types <b>int</b> and <b>float</b>, <b>int</b> operands are <i>promoted</i> to
<b>float</b>. In our example, after <b>counter</b> is promoted to
<b>float</b>, the calculation is performed and the result of the
floating-point division is assigned to <b>average</b>. Later in
this chapter we discuss all the standard data types and
their order of promotion.<br>
<spacer width=16 height=1>Cast operators are available for any data type. The
<b>static_cast</b> operator is formed by following keyword
<b>static_cast</b> with angle brackets (<b><</b> and <b>></b>) around a data
type name. The cast operator is a <i>unary operator</i>, i.e.,
an operator that takes only one operand. In Chapter 1,
we studied the binary arithmetic operators. C++ also
supports unary versions of the plus (<b>+</b>) and minus (<b>-</b>) <br>
</page>
<page>
operators, so the programmer can write expressions like
<b>-7</b> or <b>+5</b>. Cast operators associate from right to left and
have higher precedence than other unary operators such
as unary <b>+</b> and unary <b>-</b>. This precedence is higher than
that of the <i>multiplicative operators</i> <b>*</b>, <b>/</b>, and <b>%</b>, and
lower than that of parentheses. We indicate the cast
operator with the notation <b>static_cast< type>()</b> in our
precedence charts.<br>
<spacer width=16 height=1>The formatting capabilities in <a href="^Code::c:s0p1"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.9</a> are explained in
depth in Chapter 11 and discussed here briefly. The call
<b>setprecision(2)</b> in the output statement <br>
</page>
<page>
<font size=2><br></font><font size=11><pre>
cout << "Class average is " << setprecision( 2 )<p>
<< setiosflags(ios::fixed | ios::showpoint)<p>
<< average << endl;<p>
</pre></font>
indicates that <b>float</b> variable <b>average</b> is to be printed
with two digits of <i>precision</i> to the right of the decimal
point (e.g., 92.37). This call is referred to as a
<i>parameterized stream manipulator</i>. Programs that use
these calls must contain the preprocessor directive<br>
<font size=2><br></font><font size=11><pre>
#include <iomanip.h><p>
</pre></font>
Note that <b>endl</b> is a <i>nonparameterized stream
manipulator</i> and does not require the <b>iomanip.h</b> header
file. If the precision is not specified, floating-point
values are normally output with six digits of precision <br>
</page>
<page>
(i.e., the <i>default precision</i>), although we will see an
Dividing 22 by 8 yields this data type.<component type="drop" width=160 height=18 name="int"> <br>
Type of repetition where the number of repetitions is not known in advance.<component type="drop" width=160 height=18 name="sentinel-controlled"> <br>
Operator used to convert from one data type to another.<component type="drop" width=160 height=18 name="static_cast"> <br>
Type of repetition where the number of repetitions in known in advance.<component type="drop" width=160 height=18 name="counter-controlled"> <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures)">
<page>
<font size=18 bold>2.10 Formulating Algorithms with Top-
Down, Stepwise Refinement: Case Study 3
(Nested Control Structures)</font><hr>
Let us work another complete problem. We will once
again formulate the algorithm using pseudocode and
top-down, stepwise refinement, and write a
corresponding C++ program. We have seen that control
structures may be stacked on top of one another (in
sequence) just as a child stacks building blocks. In this
case study we will see the only other structured way
control structures may be connected in C++, namely
through <i>nesting</i> of one control structure within another.<br>
</page>
<page>
Consider the following problem statement:<br>
<font size=6><br></font><indent width=16><font size=14><i>A college offers a course that prepares students for the
state licensing exam for real estate brokers. Last year,
several of the students who completed this course took the
licensing examination. Naturally, the college wants to
know how well its students did on the exam. You have
been asked to write a program to summarize the results.
You have been given a list of these 10 students. Next to
each name is written a 1 if the student passed the exam
and a 2 if the student failed.</i></font></indent><font size=6><br></font>
Your program should analyze the results of the exam as
follows:<br>
</page>
<page>
1. Input each test result (i.e., a 1 or a 2). Display the
message "Enter result" on the screen each time the program requests another test result.<br>
2. Count the number of test results of each type.<br>
3. Display a summary of the test results indicating the
number of students who passed and the number of students who failed.<br>
4. If more than 8 students passed the exam, print the
message "Raise tuition."<br>
After reading the problem statement carefully, we make
the following observations:<br>
</page>
<page>
1. The program must process 10 test results. A counter-
controlled loop will be used.<br>
2. Each test result is a number--either a 1 or a 2. Each
time the program reads a test result, the program must
determine if the number is a 1 or a 2. We test for a 1 in
our algorithm. If the number is not a 1, we assume that
it is a 2. (An exercise at the end of the chapter considers
the consequences of this assumption.)<br>
3. Two counters are used--one to count the number of
students who passed the exam and one to count the
number of students who failed the exam.<br>
4. After the program has processed all the results, it
must decide if more than 8 students passed the exam.<br>
</page>
<page>
Let us proceed with top-down, stepwise refinement. We
begin with a pseudocode representation of the top:<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Analyze exam results and decide if tuition should be raised</i></font></indent><font size=3><br></font>
Once again, it is important to emphasize that the top is a
complete representation of the program, but several
<font size=3><br></font><indent width=20><font color=blue size=12><i>Initialize passes to zero<spacer width=20 height=1><p>
Initialize failures to zero<spacer width=20 height=1><p>
Initialize student counter to one<spacer width=20 height=1></i></font></indent><font size=3><br></font>
</page>
<page>
Notice only the counters and totals are initialized. The
pseudocode statement<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Input the ten quiz grades and count passes and failures</i></font></indent><font size=3><br></font>
requires a loop that successively inputs the result of
each exam. Here it is known in advance that there are
precisely ten exam results, so counter-controlled
looping is appropriate. Inside the loop (i.e., <i>nested</i>
within the loop) a double-selection structure will
determine whether each exam result is a pass or a
failure, and will increment the appropriate counter
accordingly. The refinement of the preceding
pseudocode statement is then<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>While student counter is less than or equal to ten<p></i></font></indent><font size=3><br></font>
</page>
<page>
<font size=3><br></font><indent width=20><font color=blue size=12><i><spacer width=20 height=1>Input the next exam result</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i><spacer width=20 height=1>If the student passed<p>
<spacer width=20 height=1><spacer width=20 height=1>Add one to passes<p>
<spacer width=20 height=1>else<p>
<spacer width=20 height=1><spacer width=20 height=1>Add one to failures</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i><spacer width=20 height=1>Add one to student counter</i></font></indent><font size=3><br></font>
Notice the use of blank lines to set off the <b>If/else</b> control
structure to improve program readability. The
pseudocode statement<br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Print a summary of the exam results and decide if tuition should be
The complete second refinement appears in <a href="^Illustration::c:s0p10"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.10</a>.
Notice that blank lines are also used to set off the <b>while</b>
structure for program readability.<br>
<spacer width=16 height=1> <a href="^Engineer::c:s0p10"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>This pseudocode is now sufficiently refined for
conversion to C++. The C++ program and two sample
executions are shown in <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.11</a>. Note that we have
taken advantage of a feature of C++ that allows variable
initialization to be incorporated into declarations.
Looping programs may require initialization at the
beginning of each repetition; such <a href="^Practice::c:s0p13"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>initialization would
<a href="^Engineer::c:s0p12"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>normally occur in assignment statements.<br>
where ope<a href="^Perform::c:s0p3"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>rator is one of the binary operators <b>+</b>, <b>-</b>, <b>*</b>, <b>/</b>,
or <b>%</b> (or others we will discuss later in the text), can be
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.12 Increment and Decrement Operators">
<page>
<font size=18 bold>2.12 Increment and Decrement Operators</font><hr>
C++ also provides the <b>++</b> unary <i>increment operator</i> and
the <b>--</b> unary <i>decrement operator</i> that are summarized in
<a href="^Illustration::c:s0p12"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.13</a>. If a variable <b>c</b> is incremented by 1, the
increment operator <b>++</b> can be used rather than the
expressions <b>c = c + 1</b> or <b>c += 1</b>. If an increment or
decrement operator is placed before a variable, it is
referred to as the <i>preincrement</i> or <i>predecrement</i>
<i>operator</i>, respectively. If an increment or decrement
operator is placed after a variable, it is referred to as the
<i>postincrement</i> or <i>postdecrement</i> <i>operator</i>, respectively.
Preincrementing (predecrementing) a variable causes <br>
</page>
<page>
the variable to be incremented (decremented) by 1, then
the new value of the variable is used in the expression
in which it appears. Postincrementing
(postdecrementing) a variable causes the current value
of the variable to be used in the expression in which it
appears, then the variable value is incremented
(decremented) by 1. <br>
<spacer width=16 height=1>The program of <a href="^Code::c:s0p3"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.14</a> demonstrates the difference
between the preincrementing version and the
postincrementing version of the <b>++</b> operator.
Postincrementing the variable <b>c</b> causes it to be
incremented after it is used in the output statement. <br>
</page>
<page>
Preincrementing the variable <b>c</b> causes it to be
incremented before it is used in the output statement.<br>
<spacer width=16 height=1>The program displays the value of <b>c</b> before and after the
<b>++</b> operator is used. <a href="^Practice::c:s0p14"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The decrement operator (<b>--</b>) works
similarly. <br>
<spacer width=16 height=1>The three assignment statements in <a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig 2.11
</a><br>
<font size=2><br></font><font size=11><pre>
passes = passes + 1;<p>
failures = failures + 1;<p>
student = student + 1;<p>
</pre></font>
can be written more concisely with assignment
operators as<br>
<font size=2><br></font><font size=11><pre>
passes += 1;<p>
failures += 1;<p>
student += 1;<p>
</pre></font>
</page>
<page>
with preincrement operators as<br>
<font size=2><br></font><font size=11><pre>
++passes;<p>
++failures;<p>
++student;<p>
</pre></font>
or with postincrement operators as<br>
<font size=2><br></font><font size=11><pre>
passes++;<p>
failures++;<p>
student++;<p>
</pre></font>
Note that when incrementing or decrementing a
variable in a statement by itself, the preincrement and
postincrement forms have the same effect, and the
predecrement and postdecrement forms have the same
effect. It is only when a variable appears in the context <br>
</page>
<page>
of a larger expression that preincrementing the variable
and postincrementing the variable have different effects
(and similarly for predecrementing and
postdecrementing).<br>
<spacer width=16 height=1><a href="^Errors::c:s0p13"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>For now, only a simple variable name may be used as
the operand of an increment or decrement operator (we
will see that these operators may be used on so-called
<i>lvalues</i>).<br>
<spacer width=16 height=1><a href="^Illustration::c:s0p13"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.15</a> shows the precedence and associativity of
the operators introduced to this point. The operators are
shown top-to-bottom in decreasing order of precedence.
The second column describes the associativity of the
operators at each level of precedence. Notice that the <br>
</page>
<page>
conditional operator (<b>?:</b>), the unary operators increment
(<b>++</b>), decrement (<b>--</b>), plus (<b>+</b>), minus (<b>-</b>) and casts, and
the assignment operators <b>=</b>, <b>+=</b>, <b>-=</b>, <b>*=</b>, <b>/=</b> and <b>%=</b>
associate from right to left. All other operators in the
operator precedence chart of <a href="^Illustration::c:s0p13"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.15</a> associate from
left to right. The third column names the various groups
The unary decrement operator subtracts one from a variable. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The associativity is right to left.">
The increment operator has left-to-right associativity. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The increment and decrement operators can only be applied to variables.">
The following expression is valid: cout << ++8;. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. In the context of larger expressions, predecrementing or postdecrementing can produce different results.">
Predecrementing and postdecrementing are always equivalent; regardless of the expression. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.13 Essentials of Counter-Controlled Repetition">
<page>
<font size=18 bold>2.13 Essentials of Counter-Controlled Repetition</font><hr>
Counter-controlled repetition requires:<br>
1. The <i>name</i> of a control variable (or loop counter).<br>
2. The <i>initial value</i> of the control variable.<br>
3. The condition that tests for the <i>final value</i> of the control variable (i.e., whether looping should continue).<br>
4. The <i>increment</i> (or <i>decrement</i>) by which the control
variable is modified each time through the loop.<br>
Consider the simple program shown in <a href="^Code::c:s0p4"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.16</a>,
which prints the numbers from 1 to 10. The declaration <br>
<font size=2><br></font><font size=11><pre>
int counter = 1; <p>
</pre></font>
</page>
<page>
<i>names</i> the control variable (<b>counter</b>), declares it to be
an integer, reserves space for it in memory, and sets it to
an <i>initial value</i> of <b>1</b>. Declarations that require
initialization are, in effect, executable statements. In
C++, it is more precise to call a declaration that also
reserves memory--as the preceding declaration does--
a <i>definition</i>.<br>
<spacer width=16 height=1>The declaration and initialization of <b>counter</b> also could
have been accomplished with the statements<br>
<font size=2><br></font><font size=11><pre>
int counter;<p>
counter = 1;<p>
</pre></font>
The declaration is not executable, but the assignment is.
We use both methods of initializing variables. <br>
</page>
<page>
The statement<br>
<font size=2><br></font><font size=11><pre>
++counter;<p>
</pre></font>
<i>increments</i> the loop counter by 1 each time the loop is
performed. The loop-continuation condition in the
<b>while</b> structure tests if the value of the control variable
is less than or equal to <b>10</b> (the last value for which the
condition is <b>true</b>). Note that the <a href="^Practice::c:s0p15"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>body of this <b>while</b> is
performed even when the control variable is <b>10</b>. The
loop terminates when the control variable exceeds <b>10</b>
(i.e., <b>counter</b> becomes <b>11</b>).<br>
<spacer width=16 height=1><a href="^Practice::c:s0p18"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar> </a>The program in <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.16</a> can be made more concise
by initializing <b>counter</b> to <b>0</b> and by replacing the <b>while</b>
structure with<br>
</page>
<page>
<font size=2><br></font><font size=11><pre>
while ( ++counter <= 10 ) <p>
cout << counter << endl;<p>
</pre></font>
<a href="^Practice::c:s0p16"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>This code saves a statement because the incrementing is
done directly in the <b>while</b> condition before the
condition is tested. <a href="^Practice::c:s0p17"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>Also, this code eliminates the braces
around <a href="^Errors::c:s0p14"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>the body of the <b>while</b> because the <b>while</b> now
contains only one statement. Coding in such a
condensed <a href="^Practice::c:s0p19"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>fashion takes some practice.<br>
Declarations are not considered executable statements. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A variable can be incremented in the while loop condition.">
A variable cannot be incremented in a while loop's condition. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.14 The for Repetition Structure">
<page>
<font size=18 bold>2.14 The <tt>for</tt> Repetition Structure</font><hr>
The <b>for</b> repetition structure handles all the details of
counter-controlled repetition. To illustrate the power of
<b>for</b>, let us rewrite the program of <a href="^Code::c:s0p4"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.16</a>. The result
is shown in <a href="^Code::c:s0p5"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.17</a>. The program operates as follows. <br>
<spacer width=16 height=1>When the <b>for</b> structure begins executing, the control
variable <b>counter</b> is declared and initialized to 1. Then,
the loop-continuation condition <b>counter <= 10</b> is
checked. Because the initial value of <b>counter</b> is 1, the
condition is satisfied, so the body statement prints the
value of <b>counter</b>, namely 1. The control variable
<b>counter</b> is then incremented in the expression <br>
</page>
<page>
<b>counter++</b>, and the loop begins again with the loop-
continuation test. Because the control variable is now
equal to 2, the final value is not exceeded, so the
program performs the body statement again. This
process continues until the control variable <b>counter</b> is
incremented to 11--this causes the loop-continuation
test to fail and repetition terminates. The program
continues by performing the first statement after the <b>for</b>
structure (in this case, the <b>return</b> statement at the end
of the program). <br>
<spacer width=16 height=1> <a href="^Illustration::c:s0p14"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.18</a> takes a closer look at the <b>for</b> structure of
<a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.17</a>. Notice that the <b>for</b> structure "does it all"--it
specifies each of the items needed for counter-<br>
</page>
<page>
controlled repetition with a control variable. If there is
more than one statement in the body of the <b>for</b>, braces
are required to define the body of the loop. <br>
<spacer width=16 height=1>Notice that <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.17</a> uses the loop-continuation
condition <b>counter <= 10</b>. If the programmer incorrectly
wrote <b>counter < 10</b>, then the loop would be executed
only 9 times. <a href="^Errors::c:s0p15"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>This is a common logic error <a href="^Practice::c:s0p21"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>called an
<i>off-by-one error</i>.<br>
The general format of the <b>for</b> structure is <br>
<font size=2><br></font><font size=11><pre>
for ( <i>expression1</i>; <i>expression2</i>; <i>expression3 </i>) <p>
<i>statement</i><p>
</pre></font>
where <i>expression1</i> initializes the loop's control
variable, <i>expression2</i> is the loop-continuation <br>
</page>
<page>
condition, and <i>expression3</i> increments the control
variable. In most cases the <b>for</b> structure can be
represented with an equivalent <b>while</b> structure as
follows:<br>
<font size=2><br></font><font size=11><pre>
<i>expression1</i>;<p>
while ( <i>expression2 </i>) {<p>
<i>statement<p>
</i> <i>expression3</i>;<p>
}<p>
</pre></font>
There is an exception to this rule which we will discuss
in <a href="#s18p0">Section 2.18</a>. <br>
<spacer width=16 height=1>If <i>expression1</i> (the initialization section) in the <b>for</b>
structure header defines the control variable (i.e., the <br>
</page>
<page>
control variable's type is specified before the variable
name), the control variable can only be used in the body
of the <b>for</b> structure, i.e., the value of the control
variable will be unknown outside the <b>for</b> structure. <a href="^Errors::c:s0p16"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>This
restricted use of the control variable name is known as
the variable's <i>scope</i>. The sc<a href="^Portable::c:s0p0"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>ope of a variable defines
where it can be used in a program. Scope is discussed in
detail in Chapter 3, "Functions."<br>
<spacer width=16 height=1>Sometimes, <i>expression1</i> and <i>expression3</i> are comma-
separated lists of expressions. The commas as used here
are <i>comma operators</i> that guarantee lists of expressions
evaluate left to right. The comma operator has the
lowest precedence of all operators in C++. The value <br>
</page>
<page>
and type of a comma-separated list of expressions is the
value and type of the rightmost expression in the list.
The comma operator is most often used in <b>for</b>
structures. Its primary application is to enable the
programmer to use multiple <a href="^Practice::c:s0p24"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>initialization expressions
and/or multiple increment expressions. For example,
there may be several control variables in a single <b>for</b>
structure that must be initialized and incremented. <br>
<spacer width=16 height=1>The three expressions in the <b>for</b> structure are optional.
If <i>expression2</i> is omitted, C++ assumes that the loop-
continuation condition is true, thus creating an infinite
loop. One might omit <i>expression1</i> if the control variable
is initialized elsewhere in the program. <i>expression3</i> <br>
</page>
<page>
might be omitted if the increment is calculated by
statements in the body of the <b>for</b> or if no increment is
needed. The increment expression in the <b>for</b> structure
acts like a stand-alone statement at the end of the body
of the <b>for</b>. Therefore, the expressions<br>
<font size=2><br></font><font size=11><pre>
counter = counter + 1<p>
counter += 1<p>
++counter<p>
counter++<p>
</pre></font>
are all equivalent in the incrementing portion of the <b>for</b>
structure. Many programmers prefer the form
<b>counter++</b> because the incrementing occurs after the
loop body is executed. The postincrementing form <br>
</page>
<page>
therefore seems more natural. Because the variable
being incremented here does not appear in an
expression, both preincrementing and postincrementing
have the same effect. <a href="^Errors::c:s0p19"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The two semicolons in the <b>for</b>
The next two examples provide simple applications of
the <b>for</b> structure. The program of <a href="^Code::c:s0p6"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.20</a> uses the <b>for</b>
structure to sum all the even integers from <b>2</b> to <b>100</b>. <br>
<spacer width=16 height=1>Note that the body of the <b>for</b> structure in <a href="^Code::c:s0p6"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.20</a>
could actually be merged into the rightmost portion of
the <b>for</b> header by using the comma operator as follows:<br>
<font size=2><br></font><font size=11><pre>
for ( int number = 2; // initialization<p>
number <= 100; // continuation condition<p>
sum += number, number += 2) // total and increment<p>
;<p>
</pre></font>
The initialization <b>sum = 0</b> could also be <a href="^Practice::c:s0p27"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>merged into the
initialization section of the <b>for</b>.<br>
</page>
<page>
<a href="^Practice::c:s0p28"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The next example computes compound interest using
the <b>for</b> structure. Consider the following problem
statement: <br>
<font size=6><br></font><indent width=16><font size=14><i>A person invests $1000.00 in a savings account yielding 5
percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of
money in the account at the end of each year for 10 years.
Use the following formula for determining these amounts:</i></font></indent><font size=6><br></font>
<i>p</i> is the original amount invested (i.e., the principal),<p>
<i>r</i> is the annual interest rate,<p><p>
</pre></font>
</page>
<page>
<font size=2><br></font><font size=11><pre>
<i>n</i> is the number of years, and<p>
<i>a</i> is the amount on deposit at the end of the <i>n</i>th year.<p>
</pre></font>
This problem involves a loop that performs the
indicated calculation for each of the 10 years the money
remains on deposit. The solution is shown in <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.21</a>. <br>
<spacer width=16 height=1>The <b>for</b> structure executes the body of the loop 10
times, varying a control variable from 1 to 10 in
increments of 1. C++ does not include an
exponentiation operator, so we use the standard library
function <b>pow</b> for this purpose. The function <b>pow( x, y )</b>
calculates the value of <b>x</b> raised to the <b>y</b>th power.
Function <b>pow</b> takes two arguments of type <b>double</b> and <br>
</page>
<page>
returns a <b>double</b> value. The type <b>double</b> is a floating-
point type much like <b>float</b>, but a variable of type
<b>double</b> can store a value of much greater magnitude
with greater precision than <b>float</b>. Constants (like <b>1000.0</b>
and <b>.05</b> in <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.21</a>) are treated as being type <b>double</b>
by C++.<br>
This program would not compile without the inclusion
of<b> math.h</b>. Function <b>pow</b> requires two <b>double</b>
arguments. Note that <b>year</b> is an integer. <a href="^Errors::c:s0p22"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The <b>math.h</b> file
includes information that tells the compiler to convert
the value of <b>year</b> to a temporary <b>double</b> representation
before calling the function. This information is
contained in <b>pow</b>'s <i>function prototype</i>. Function <br>
</page>
<page>
prototypes are explained in Chapter 3. We provide a
summary of the <b>pow</b> function and other math library
functions in Chapter 3. <br>
<spacer width=16 height=1>Notice that we declared the variables <b>amount</b>,
<b>principal</b>, and <b>rate</b> to be of type <b>double</b>. We have done
this for simplicity because we are dealing with
fractional parts of dollars and we need a type that
allows decimal points in its values. Unfortunately, this
can cause trouble. Here is a simple explanation of what
can go wrong when using <b>float</b> or <b>double</b> to represent
dollar amounts (assuming printing is done with
<b>setprecision(2)</b>): Two <b>float</b> dollar amounts stored in the
machine could be 14.234 (which prints as 14.23) and <br>
</page>
<page>
18.673 (which prints as 18.67). When these amounts
are added, they produce the internal sum 32.907 which
prints as 32.91. Thus your printout could appear as<br>
<font size=2><br></font><font size=11><pre>
14.23<p>
+ 18.67<p>
-------<p>
32.91<p>
</pre></font>
but a person adding the individual numbers as printed
would expect the sum 32.90! <a href="^Practice::c:s0p29"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>You have been warned!<br>
justified in a field of 21 character positions (specified
with <b>setw( 21 )</b>) and two digits of precision to the right
of the decimal point (specified with <b>setprecision( 2 )</b>).
We will discuss the powerful input/output formatting
capabilities of C++ in detail in Chapter 11.<br>
<spacer width=16 height=1>Note that the calculation <b>1.0 + rate</b> which appears as an
argument to the <b>pow</b> function is contained in the body
of the <b>for</b> statement. <a href="^Perform::c:s0p8"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>In fact, this calculation produces <br>
</page>
<page>
the same result each time through the loop, so <a href="^Perform::c:s0p7"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>repeating
the calculation is wasteful. <br>
<spacer width=16 height=1>For fun, be sure to try our Peter Minuet problem in the
chapter exercises. This problem demonstrates the
wonders of compound interest.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The language does not include an exponentiation operator.">
The C++ language includes an exponentiation operator. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. A double can store a larger number with a much greater precision than a float.">
A float can store a number with a much greater precision and magnitude than a double. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Floating point numbers are approximated on most systems.">
Floating point numbers are represented exactly on most systems. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.16 The switch Multiple-Selection Structure">
<page>
<font size=18 bold>2.16 The <b>switch</b> Multiple-Selection Structure</font><hr>
We have discussed the <b>if</b> single-selection structure and
the <b>if/else</b> double-selection structure. Occasionally, an
algorithm will contain a series of decisions in which a
variable or expression is tested separately for each of
the constant integral values it may assume, and
different actions are taken. C++ provides the <b>switch</b>
multiple-selection structure to handle such decision
making. <br>
<spacer width=16 height=1>The <b>switch</b> structure consists of a series of <b>case</b> labels,
and an optional <b>default</b> case. The program in <a href="^Code::c:s0p8"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.22</a> <br>
</page>
<page>
uses <b>switch</b> to count the number of each different letter
grade that students earned on an exam. <spacer width=20 height=1><br>
In the program, the user enters letter grades for a class.
Inside the <b>while</b> header,<br>
<font size=2><br></font><font size=11><pre>
while ( ( grade = cin.get() ) != EOF)<p>
</pre></font>
the parenthesized assignment <b>( grade = cin.get() )</b> is
executed first. The <b>cin.get()</b> function reads one
character from the keyboard and stores that character in
integer variable <b>grade</b>. The dot notation used in
<b>cin.get()</b> will be explained in Chapter 6, "Classes."
Characters are normally stored in variables of type
<b>char</b>. However, an important feature of C++ is that <br>
</page>
<page>
characters can be stored in any integer data type
because they are represented as 1-byte integers in the
computer. Thus, we can treat a character as either an
integer or a character depending on its use. For
example, the statement<br>
<font size=2><br></font><font size=11><pre>
cout << "The character (" << 'a' << ") has the value " <p>
<< static_cast< int > ( 'a' ) << endl;<p>
</pre></font>
prints the character <b>a</b> and its integer value as follows<br>
<font size=2><br></font><font size=11><pre>
The character (a) has the value 97<p>
</pre></font>
The integer 97 is the character's numerical
representation in the computer. Many computers today
use the<i> ASCII (American Standard Code for
</i><br>
</page>
<page>
<i>Information Interchange) character set</i> in which 97
represents the lowercase letter <b>'a'</b>. A list of the ASCII
characters and their decimal values is presented in the
appendices. <br>
<spacer width=16 height=1>Assignment statements as a whole have the value that is
assigned to the variable on the left side of the <b>=</b>. Thus,
the value of the assignment <b>grade = cin.get()</b> is the
same as the value returned by <b>cin.get()</b> and assigned to
the variable <b>grade</b>. <br>
<spacer width=16 height=1>The fact that assignment statements have values can be
useful for initializing several variables to the same
value. For example, <br>
<font size=2><br></font><font size=11><pre>
a = b = c = 0;<p>
</pre></font>
</page>
<page>
first evaluates the assignment <b>c = 0</b> (because the <b>=</b>
operator associates from right to left). The variable <b>b</b> is
then assigned the value of the assignment <b>c = 0</b> (which
is 0). Then, the variable <b>a</b> is assigned the value of the
assignment <b>b = (c = 0)</b> (which is also 0). In the
program, the value of the assignment <b>grade = cin.get()</b>
is compared with the value of <b>EOF</b> (a symbol whose
acronym stands for "end-of-file"). We use <b>EOF</b> (which
normally has the value 1) as the sentinel value. The
user types a system-dependent keystroke combination
to mean "end-of-file," i.e., "I have no more data to
enter." <b>EOF</b> is a symbolic integer constant defined in
the <b><iostream.h></b> header file. If the value assigned to <br>
</page>
<page>
<b>grade</b> is equal <b><a href="^Portable::c:s0p5"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a></b>to <b>EOF</b>, the program terminates. We
have chosen to represent characters in this program as
<b>int</b>s <b><a href="^Portable::c:s0p3"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a></b>because <b>EOF</b> has an integer value (again, normally
1). <br>
<spacer width=16 height=1>On UNIX systems and many others, end-of-file is
entered by typing the sequence<br>
<font size=2><br></font><font size=11><pre>
<<i>ctrl-d</i>><p>
</pre></font>
on a line by itself. This notation means to
simultaneously press both the <b>ctrl</b> key and the <b>d</b> key.
On other systems such as Digital Equipment
Corporation's VAX VMS or Microsoft Corporation's
MS-DOS, end-of-file can be entered by typing <br>
<font size=2><br></font><font size=11><pre>
<<i>ctrl-z</i>><p>
</pre></font>
</page>
<page>
The user enters grades at the keyboard. When the <i>Enter</i>
(or <i>Return</i>) key is pressed, the characters are read by the
<b>cin.get()</b> function one character at a time. If the
character entered is not end-of-file, the <b>switch</b> structure
is entered. The keyword <b>switch</b> is followed by the
variable name <b>grade</b> in parentheses. This is called the
<i>controlling expression</i>. The value of this expression is
compared with each of the <b>case</b> <i>labels</i>. Assume the user
has entered the letter <b>C</b> as a grade. <b>C</b> is automatically
compared to each <b>case</b> in the <b>switch</b>. If a match occurs
(<b>case 'C':</b>), the statements for that <b>case</b> are executed.
For the letter <b>C</b>, <b>cCount</b> is incremented by <b>1</b>, and the
<b>switch</b> structure is exited immediately with the <b>break</b> <br>
</page>
<page>
statement. Note that unlike other control structures, it is
not necessary to enclose a multistatement <b>case</b> in
braces.<br>
<spacer width=16 height=1>The <b>break</b> statement causes program control to proceed
with the first statement after the <b>switch</b> structure. The
<b>break</b> statement is used because the <b>case</b>s in a <b>switch</b>
statement would otherwise run together. If <b>break</b> is not
used anywhere in a <b>switch</b> structure, then each time a
match occurs in the structure, the statements for all the
remaining <b>case</b>s will be executed. (This feature is
sometimes useful when performing the same actions for
several <b>case</b>s, as in the program of<a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.22</a>.) If no <br>
</page>
<page>
match occurs, the <b>default</b> case is executed and an error
message is printed. <br>
<spacer width=16 height=1>Each <b>case</b> can have one or more actions. The <b>switch</b>
structure is different from all other structures in that
braces are not required around multiple actions in a
<b>case</b> of a <b>switch</b>. The general <b>switch</b> multiple-selection
structure (using a <b>break</b> in each <b>case</b>) is flowcharted in
<spacer width=16 height=1><a href="^Errors::c:s0p25"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The flowchart makes it clear that each <b>break</b> statement
at the end of a <b>case</b> <b><a href="^Errors::c:s0p23"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a></b>causes control to immediately exit
the <b>switch</b> structure. Again, note that (besides small
circles and arrows) the flowchart contains only
rectangle symbols and diamond symbols. Imagine, <br>
</page>
<page>
again, that the programmer has access to a deep bin of
empty <b>switch</b> structures--as many as the programmer
might need to stack and nest with other control
structures to form a structured implementation of an
<a href="^Practice::c:s0p33"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>algorithm's flow of control. And again, the rectangles
and diamonds are then filled with actions and decisions
<a href="^Practice::c:s0p32"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>appropriate to the algorithm. Nested control structures
are common, but it is rare to find <b><a href="^Practice::c:s0p31"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a></b>nested <b>switch</b>
structures in a program.<br>
<spacer width=16 height=1>In the <b>switch</b> structure of <a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.22</a>, lines 46-49<br>
<font size=2><br></font><font size=11><pre>
case '\n': <p>
case '\ ': <p>
case ' ':<p>
break;<p>
</pre></font>
</page>
<page>
cause the program to skip newline, tab and blank
characters. Reading characters one at a time can cause
some problems. To have the program read the
characters, they must be sent to the computer by
pressing the <i>Enter key </i>on the keyboard. This places a
newline character in the input after the character we
wish to process. Often, this newline character must be
specially processed to make the program work
correctly. By including the preceding cases in our
<b>switch</b> structure, we prevent the error message in the
<b>default</b> case from being printed each time a <a href="^Errors::c:s0p26"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>newline,
tab or space is encountered in the input.<br>
</page>
<page>
Note that several case labels listed together (such as
<b>case 'D': case 'd':</b> in <a href="^Code::c:s0p8"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.22</a>) simply means that the
same set of actions is to occur for each of the cases.<br>
<spacer width=16 height=1>When using the <b>switch</b> structure, remember that it can
only be used for testing a <i>constant integral expression</i>,
i.e., any combination of character constants and integer
constants that evaluates to a constant integer value. A
character constant is represented as the specific
character in single quotes such as <b>'A'</b>. An integer
constant is simply an integer value. <br>
<spacer width=16 height=1>When we get to the part of the book on object-oriented
programming, we will present a more elegant way to
implement <b>switch</b> logic. We will use a technique called <br>
</page>
<page>
polymorphism to create programs that are often clearer,
more concise, easier to maintain, and easier to extend
than programs using <b>switch</b> logic.<br>
<spacer width=16 height=1>Portable languages like C++ must have flexible data
type sizes. Different applications may need integers of
different sizes. C++ provides several data types to
represent integers. The range of integer values for each
type depends on the particular computer's hardware. In
addition to the types <b>int</b> and <b>char</b>, C++ provides the
types <b>short</b> (an abbreviation of <b>short int</b>) and <b>long</b> (an
abbreviation of <b>long int</b>). The minimum range of values
for <b>short</b> integers is +/-<a href="^Portable::c:s0p6"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>32767. For the vast majority of
integer calculations, <b>long</b> integers are sufficient. The <br>
</page>
<page>
minimum range of values for <b>long</b> integers is +/-
2147483647. <a href="^Perform::c:s0p11"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>On most computers, <b>int</b>s are equivalent
either to <b>short</b> or to <b>long</b>. The range of values for an <b>int</b>
is <a href="^Perform::c:s0p10"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>at least the same as the range for <b>short</b> integers and
no larger than the range for <b>long</b> integers. The data type
<b>char</b> can be used to represent any of the characters in
the computer's character set. <a href="^Errors::c:s0p27"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The data type <b>char</b> can
also be used to represent small integers.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. Only constant integral expressions can be used with the switch structure.">
The switch structure can be used with any data type. <br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The break statement is optional.">
The break statement is required in a switch structure. <br>
<component type=button name=b label="Check Your Answer" width=125 height=24>
</page>
</section>
<section type=Body name=Default title="2.17 The do/while Repetition Structure">
<page>
<font size=18 bold>2.17 The <b>do/while</b> Repetition Structure</font><hr>
The <b>do/while</b> repetition structure is similar to the <b>while</b>
structure. In the <b>while</b> structure, the loop-continuation
condition is tested at the beginning of the loop before
the body of the loop is performed. The <b>do/while</b>
structure tests the loop-continuation condition <i>after</i> the
loop body is performed; therefore, the loop body will be
executed at least once. When a <b>do/while</b> terminates,
execution continues with the statement after the <b>while</b>
clause. Note that it is not necessary to use braces in the
<b>do/while</b> structure if there is only one statement in the
body. However, the braces are usually included to avoid <br>
</page>
<page>
confusion between the <b>while</b> and <b>do/while</b> structures.
For example, <br>
<font size=2><br></font><font size=11><pre>
while ( <i>condition</i> )<p>
</pre></font>
is normally regarded as the header to a <b>while</b> structure.
A <b>do/while</b> with no braces around the single statement
body appears as <br>
<font size=2><br></font><font size=11><pre>
do <p>
<i>statement<p>
</i>while ( <i>condition</i> );<p>
</pre></font>
which can be confusing. The last line--<b>while</b>(
<i>condition</i> );--may be misinterpreted by the reader as a
<b>while</b> structure containing an empty statement. Thus, <br>
</page>
<page>
the <b>do/while</b> with one statement is often written as
<a href="^Errors::c:s0p28"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>follows to avoid confusion:<br>
<font size=2><br></font><font size=11><pre>
do {<p>
<i>statement<p>
</i>} while ( condition );<p>
</pre></font>
<a href="^Practice::c:s0p35"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>The program in <a href="^Code::c:s0p9"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.24</a> uses a <b>do/while</b> repetition
structure to print the numbers from 1 to 10. Note that
the control variable <b>counter</b> is preincremented in the
loop-continuation test. Note also the use of the braces to
enclose the single-statement body of the <b>do/while</b>
structure.<br>
The <b>do/while</b> structure is flowcharted in <a href="^Illustration::c:s0p17"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.25</a>. This
flowchart makes it clear that the loop-continuation <br>
</page>
<page>
condition is not executed until after the action is
performed at least once. Again, note that (besides small
circles and arrows) the flowchart contains only a
rectangle symbol and a diamond symbol. Imagine,
again, that the programmer has access to a deep bin of
empty <b>do/while</b> structures--as many as the
programmer might need to stack and nest with other
control structures to form a structured implementation
of an algorithm's flow of control. And again, the
rectangles and diamonds are then filled with actions and
decisions appropriate to the algorithm.<br>
</page>
<page>
<b>Select the true statement(s). </b><br>
<component type="checkbox" width=20 height=18 label="" name="" feedback="False. The body is executed at least once.">
The body of a do/while is executed only if the loop-continuation condition is true. <br>
the <b>break</b> statement in a <b>for</b> repetition structure. When
the <b>if</b> structure detects that <b>x</b> has become <b>5</b>, <b>break</b> is
executed. This terminates the <b>for</b> statement and the <br>
</page>
<page>
program continues with the <b>cout</b> after the <b>for</b>. The loop
fully executes only four times.<br>
<spacer width=16 height=1>Note that the control variable <b>x</b> in this program is
defined outside the <b>for</b> structure header. This is because
we intend to use the control variable both in the body of
the loop and after the loop completes its execution.<br>
<spacer width=16 height=1>The <b>continue</b> statement, when executed in a <b>while</b>, <b>for</b>,
or <b>do/while</b> structure, skips the remaining statements in
the body of that structure, and proceeds with the next
iteration of the loop. In <b>while</b> and <b>do/while</b> structures,
the loop-continuation test is evaluated immediately
after the <b>continue</b> statement is executed. In the <b>for</b>
structure, the increment expression is executed, then the <br>
</page>
<page>
loop-continuation test is evaluated. Earlier, we stated
that the <b>while</b> structure could be used in most cases to
represent the <b>for</b> structure. The one exception occurs
when the increment expression in the <b>while</b> structure
follows the <b>continue</b> <b><a href="^Practice::c:s0p37"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a></b>statement. In this case, the
increment is not executed before the repetition-
continuation condition is tested, and the <b>while</b> does not
execute in the same manner as the <b>for</b>. <a href="^Code::c:s0p11"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 2.27</a> uses
the <b>continue</b> <b><a href="^Perform::c:s0p12"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a></b>statement in a <b>for</b> structure to skip the
output statement in the structure and begin the next
iteration of <a href="^Engineer::c:s0p16"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>the loop.<br>
So far we have studied only<i> simple conditions</i> such as
<b>counter <= 10, total > 1000</b>, and <b>number !=
sentinelValue</b>. We have expressed these conditions in
terms of the relational operators <b>></b>,<b> <</b>, <b>>=</b>, and <b><=</b>, and
the equality operators <b>==</b> and <b>!=</b>. Each decision tested
precisely one condition. To test multiple conditions
while making a decision, we performed these tests in
separate statements or in nested <b>if</b> or <b>if/else</b> structures.<br>
<spacer width=16 height=1>C++ provides <i>logical operators</i> that are used to form
more complex conditions by combining simple
conditions. The logical operators are<b> &&</b> (<i>logical</i> <br>
</page>
<page>
<i>AND</i>), <b>||</b> (<i>logical OR</i>), and <b>!</b> (<i>logical NOT</i> also called
<i>logical negation</i>). We consider examples of each of
these.<br>
<spacer width=16 height=1>Suppose we wish to ensure that two conditions are <i>both</i>
<b>true</b> before we choose a certain path of execution. In
this case we can use the logical <b>&& </b>operator as
follows:<br>
<font size=2><br></font><font size=11><pre>
if ( gender == 1 && age >= 65 )<p>
++seniorFemales;<p>
</pre></font>
This <b>if</b> statement contains two simple conditions. The
condition <b>gender == 1</b> might be evaluated, for
example, to determine if a person is a female. The
condition <b>age >= 65</b> is evaluated to determine if a <br>
</page>
<page>
person is a senior citizen. The simple condition to the
left of the <b>&&</b> operator is evaluated first because the
precedence of <b>==</b> is higher than the precedence of <b>&&</b>.
If necessary, the simple condition to the right of the <b>&&</b>
operator is evaluated next because the precedence of <b>>=</b>
is higher than the precedence of <b>&&</b> (as we will discuss
shortly, the right side of a logical AND expression is
only evaluated if the left side is <b>true</b>). The <b>if</b> statement
then considers the combined condition<br>
<font size=2><br></font><font size=11><pre>
gender == 1 && age >= 65<p>
</pre></font>
This condition is <b>true</b> if and only if both of the simple
conditions are <b>true</b>. Finally, if this combined condition
is indeed <b>true</b>, then the count of <b>seniorFemales</b> is <br>
</page>
<page>
incremented by <b>1</b>. If either or both of the simple
conditions are <b>false</b>, then the program skips the
incrementing and proceeds to the statement following
the <b>if</b>. <a href="^Errors::c:s0p30"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>The preceding combined condition can be made
more readable by adding redundant parentheses<br>
<font size=2><br></font><font size=11><pre>
( gender == 1 ) && ( age >= 65 )<p>
</pre></font>
The table of <a href="^Illustration::c:s0p18"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.28</a> summarizes the <b>&&</b> operator.
The table shows all four possible combinations of <b>false</b>
and <b>true</b> values for expression1 and expression2. Such
tables are often called <i>truth tables</i>. C++ evaluates to
<b>false</b> or <b>true</b> all <b><a href="^Portable::c:s0p7"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a></b>expressions that include relational
Now let us consider the <b>||</b> (logical OR) operator.
Suppose we wish to ensure at some point in a program
that either <i>or</i> both of two conditions are <b>true</b> before we
choose a certain path of execution. In this case we use
the || operator as in the following program segment:<br>
<font size=2><br></font><font size=11><pre>
if ( semesterAverage >= 90 || finalExam >= 90 )<p>
cout << "Student grade is A" << endl;<p>
</pre></font>
This preceding condition also contains two simple
conditions. The simple condition <b>semesterAverage >=
90</b> is evaluated to determine if the student deserves an
"A" in the course because of a solid performance
throughout the semester. The simple condition
<b>finalExam >= 90</b> is evaluated to determine if the <br>
</page>
<page>
student deserves an "A" in the course because of an
outstanding performance on the final exam. The <b>if</b>
statement then considers the combined condition<br>
<font size=2><br></font><font size=11><pre>
semesterAverage >= 90 || finalExam >= 90<p>
</pre></font>
and awards the student an "A" if either or both of the
simple conditions are <b>true</b>. Note that the message
"<b>Student grade is A</b>" is not printed only when both of
the simple conditions are <b>false</b>. <a href="^Illustration::c:s0p19"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.29</a> is a truth
table for the logical OR operator (<b>||</b>).<br>
<spacer width=16 height=1>The <b>&&</b> operator has a higher precedence than the<b> ||</b>
operator. Both operators associate from left to right. An
expression containing <b>&&</b> or <b>||</b> <a href="^Perform::c:s0p13"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>operators is evaluated <br>
</page>
<page>
only until truth or falsehood is known. Thus, evaluation
of the expression <br>
<font size=2><br></font><font size=11><pre>
gender == 1 && age >= 65<p>
</pre></font>
will <a href="^Errors::c:s0p31"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>stop immediately if <b>gender</b> is not equal to <b>1</b> (i.e.,
the entire expression is <b>false</b>), and continue if <b>gender</b> is
equal to <b>1</b> (i.e., the entire expression could still be <b>true</b>
if the condition <b>age >= 65 is true</b>).<br>
C++ provides the <b>!</b> (logical negation) operator to enable
a programmer to "reverse" the meaning of a condition.
Unlike the <b>&&</b> and <b>||</b> operators, which combine two
conditions (binary operators), the logical negation
operator has only a single condition as an operand
(unary operator). The logical negation operator is <br>
</page>
<page>
placed before a condition when we are interested in
choosing a path of execution if the original condition
(without the logical negation operator) is <b>false</b>, such as
in the following program segment:<br>
<font size=2><br></font><font size=11><pre>
if ( !( grade == sentinelValue ) )<p>
cout << "The next grade is " << grade << endl;<p>
</pre></font>
The parentheses around the condition <b>grade ==
sentinelValue</b> are needed because the logical negation
operator has a higher precedence than the equality
operator. <a href="^Illustration::c:s0p20"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.30</a> is a truth table for the logical
negation operator.<br>
<spacer width=16 height=1>In most cases, the programmer can avoid using logical
negation by expressing the condition differently with an <br>
</page>
<page>
appropriate relational or equality operator. For example,
the preceding statement may also be written as follows:<br>
<font size=2><br></font><font size=11><pre>
if ( grade != sentinelValue )<p>
cout << "The next grade is " << grade << endl;<p>
</pre></font>
This flexibility can often help a programmer express a
condition in a more "natural" or convenient manner.<br>
<spacer width=16 height=1><a href="^Illustration::c:s0p21"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.31</a> shows the precedence and associativity of
the C++ operators introduced to this point. The
operators are shown from top to bottom in decreasing
order of precedence. <br>
</page>
<page>
<b>Drag the correct term to the box associated with the
flowchart symbols to form a limited set of control
structures, and to build structured programs by properly
combining control structures in two simple ways. <br>
For simplicity, only single-entry/single-exit control
structures are used--there is only one way to enter and
only one way to exit each control structure. Connecting
control structures in sequence to form structured
programs is simple--the exit point of one control
structure is connected to the entry point of the next <br>
</page>
<page>
control structure, i.e., the control structures are simply
placed one after another in a program; we have called
this "control structure stacking." The rules for forming
structured programs also allow for control structures to
be nested.<br>
<spacer width=16 height=1><a href="^Illustration::c:s0p26"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 2.33</a> shows the rules for forming properly
structured programs. The rules assume that the
rectangle flowchart symbol may be used to indicate any
action including input/output. <br>
<spacer width=16 height=1>Applying the rules of <a href="^Illustration::c:s0p26"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.33</a> always results in a
structured flowchart with a neat, building-block
appearance. For example, repeatedly applying rule 2 to
the simplest flowchart results in a structured flowchart <br>
</page>
<page>
containing many rectangles in sequence ( <a href="^Illustration::c:s0p24"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.35</a>).
Notice that rule 2 generates a stack of control
structures; so let us call rule 2 the <i>stacking rule</i>.<br>
<spacer width=16 height=1>Rule 3 is called the <i>nesting rule</i>. Repeatedly applying
rule 3 to the simplest flowchart results in a flowchart
with neatly nested control structures. For example, in
<a href="^Illustration::c:s0p29"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.36</a>, the rectangle in the simplest flowchart is first
replaced with a double-selection (<b>if/else</b>) structure.
Then rule 3 is applied again to both of the rectangles in
the double-selection structure, replacing each of these
rectangles with double-selection structures. The dashed
boxes around each of the double-selection structures <br>
</page>
<page>
represent the rectangle that was replaced in the original
simplest flowchart.<br>
<spacer width=16 height=1>Rule 4 generates larger, more involved, and more
deeply nested structures. The flowcharts that emerge
from applying the rules in <a href="^Illustration::c:s0p26"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.33</a> constitute the set of
all possible structured flowcharts and hence the set of
all possible structured programs. <br>
<spacer width=16 height=1>The beauty of the structured approach is that we use
only seven simple single-entry/single-exit pieces, and
we assemble them in only two simple ways. <a href="^Illustration::c:s0p28"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure
2.37</a> shows the kinds of stacked building blocks that
emerge from applying rule 2 and the kinds of nested
building blocks that emerge from applying rule 3. The <br>
</page>
<page>
figure also shows the kind of overlapped building
blocks that cannot appear in structured flowcharts
(because of the elimination of the <b>goto</b> statement). <br>
<spacer width=16 height=1>If the rules in <a href="^Illustration::c:s0p26"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.33</a> are followed, an unstructured
flowchart (such as that in <a href="^Illustration::c:s0p27"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.38</a>) cannot be created.
If you are uncertain if a particular flowchart is
structured, apply the rules of <a href="^Illustration::c:s0p26"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 2.33</a> in reverse to try
to reduce the flowchart to the simplest flowchart. If the
flowchart is reducible to the simplest flowchart, the
original flowchart is structured; otherwise, it is not.<br>
a temporary floating-point copy of its operand. </indent>
</page>
<page>
<indent width=8 delay>* C++ provides the arithmetic assignment operators
<b>+=</b>, <b>-=</b>, <b>*=</b>, <b>/=</b>, and <b>%=</b> that help abbreviate certain
common types of expressions. </indent>
<indent width=8 delay>* C++ provides the increment (<b>++</b>) and decrement (<b>--</b>)
operators to increment or decrement a variable by 1. If
the operator is prefixed to the variable, the variable is
incremented or decremented by 1 first, then used in its
expression. If the operator is postfixed to the variable,
the variable is used in its expression, then incremented
or decremented by 1.</indent>
<indent width=8 delay>* A loop is a group of instructions the computer executes repeatedly until some terminating condition is satisfied. Two forms of repetition are counter-controlled </indent>
</page>
<page>
<indent width=8 delay>* repetition and sentinel-controlled repetition.</indent>
<indent width=8 delay>* A loop counter is used to count repetitions for a
group of instructions. It is incremented (or decremented) usually by 1 each time the group of instructions is performed. </indent>
<indent width=8 delay>* Sentinel values are generally used to control repetition when the precise number of repetitions is not
known in advance and the loop includes statements that
obtain data each time the loop is performed. A sentinel
value is entered after all valid data items have been supplied to the program. Sentinels should be different from
valid data items.</indent>
<indent width=8 delay>* The <b>for</b> repetition structure handles all the details of </indent>
</page>
<page>
<indent width=8 delay>* counter-controlled repetition. The general format of the
<b>for</b> structure is </indent>
<font size=2><br></font><font size=11><pre>
for ( <i>expression1</i>; <i>expression2</i>; <i>expression3</i> ) <p>
<i>statement</i><p>
</pre></font>
where <i>expression1</i> initializes the loop's control
variable, <i>expression2</i> is the loop-continuation
condition, and <i>expression3</i> increments the control
variable. <br>
<indent width=8 delay>* The <b>do/while</b> repetition structure tests the loop-continuation condition at the end of the loop, so the body of
the loop will be executed at least once. The format for
the <b>do/while</b> structure is</indent>
</page>
<page>
<font size=2><br></font><font size=11><pre>
do<p>
<i>statement<p>
</i>while ( <i>condition</i> );<p>
</pre></font>
<indent width=8 delay>* The <b>break</b> statement, when executed in one of the
repetition structures (<b>for</b>, <b>while</b>, and <b>do/while</b>), causes
immediate exit from the structure. </indent>
<indent width=8 delay>* The <b>continue</b> statement, when executed in one of the
repetition structures (<b>for</b>, <b>while</b>, and <b>do/while</b>), skips
any remaining statements in the body of the structure,
and proceeds with the next iteration of the loop.</indent>
<indent width=8 delay>* The <b>switch</b> statement handles a series of decisions in
which a particular variable or expression is tested for
values it may assume, and different actions are taken. In </indent>
</page>
<page>
<indent width=8 delay>* most programs, it is necessary to include a <b>break</b> statement after the statements for each <b>case</b>. Several <b>case</b>s
can execute the same statements by listing the <b>case</b>
labels together before the statements. The <b>switch</b> structure can only test constant integral expressions. It is not
necessary to enclose a multistatement <b>case</b> in braces.</indent>
<indent width=8 delay>* On UNIX systems and many others, end-of-file is
entered by typing the sequence</indent>
<font size=2><br></font><font size=11><pre>
<i><ctrl-d></i> <p>
</pre></font>
on a line by itself. On VMS and DOS, end-of-file is
entered by typing <br>
<font size=2><br></font><font size=11><pre>
<i><ctrl-z></i> <p>
</pre></font>
</page>
<page>
<indent width=8 delay>* Logical operators may be used to form complex conditions by combining conditions. The logical operators
are <b>&&</b>,<b> ||</b>, and <b>!</b>, meaning logical AND, logical OR,
and logical NOT (negation), respectively.</indent>
<indent width=8 delay>* A <b>true</b> value is any nonzero value; a <b>false</b> value is 0
<font size=3><br></font><indent width=20><font color=blue size=12><i>While grade counter is less than or equal to ten</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Input the next grade</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Add the grade into the total</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Add one to the grade counter</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Set the class average to the total divided by ten</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Print the class average</i></font></indent><font size=3><br></font>
<br>
</page>
<page>
<font size=18><a href="~audio/Ch02/02fig008.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 2.8 - Pseudocode algorithm that uses sentinel-controlled repetition to solve
the class average problem.</font><br>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Initialize total to zero</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Initialize counter to zero</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>Input the first grade (possibly the sentinel)</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>While the user has not as yet entered the sentinel </i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Add this grade into the running total</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Add one to the grade counter</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Input the next grade (possibly the sentinel)</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>If the counter is not equal to zero</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Set the average to the total divided by the counter</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i> Print the average</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i>While student counter is less than or equal to ten</i></font></indent><font size=3><br></font>
<font size=3><br></font><indent width=20><font color=blue size=12><i><spacer width=20 height=1>Input the next exam result</i></font></indent><font size=3><br></font>
<font size=18><a href="~audio/Ch02/02fig013.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 2.13 - The increment and decrement operators.<img src="graphics/ch02/fig02013.gif" ></font><br>
</page>
<page>
<font size=18><a href="~audio/Ch02/02fig015.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 2.15 - Precedence of the operators encountered so far in the text.<img src="graphics/ch02/fig02015.gif" ></font><br>
</page>
<page>
<font size=18><a href="~audio/Ch02/02fig018.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 2.18 - Components of a typical <b>for</b> header.<img src="graphics/ch02/fig02018.gif" ></font><br>
<indent width=8 delay>* To understand basic problem solving techniques.</indent>
<indent width=8 delay>* To be able to develop algorithms through the process of top-down, stepwise refinement.</indent>
<indent width=8 delay>* To be able to use the <b>if</b>, <b>if/else</b>, and <b>switch</b> selection structures to choose
among alternative actions.</indent>
<foreign name="audio" url="~audio/Ch02/02obj.au">
</page>
<page>
<indent width=8 delay>* To be able to use the <b>while</b>, <b>do/while</b>, and <b>for</b> repetition structures to execute statements in a program repeatedly.</indent>
<indent width=8 delay>* To understand counter-controlled repetition and sentinel-controlled repetition.</indent>
<indent width=8 delay>* To be able to use the increment, decrement, assignment, and logical operators.</indent>
</page>
<page>
<indent width=8 delay>* To be able to use the <b>break</b> and <b>continue</b> program control statements.</indent>
Exercises 2.1 through 2.10 correspond to Sections 2.1 through 2.12.<br>
Exercises 2.11 through 2.13 correspond to Sections 2.13 through 2.21.<br>
<br>
Answer each of the following questions.<br>
a) All programs can be written in terms of three types of control structures:
_______, ________, and ________.<br>
b) The ________selection structure is used to execute one action when a
condition is <b>true</b> and another action when that condition is <b>false</b>.<br>
c) Repetition of a set of instructions a specific number of times is called<p>
_______ repetition.<br>
<foreign name="answers" url="^Answers::c:s0p0">
</page>
<page pagename="Exercise 2.1">
d) When it is not known in advance how many times a set of statements will be
repeated, a________value can be used to terminate the repetition.<br>
<foreign name="answers" url="^Answers::c:s0p0">
</page>
<page pagename="Exercise 2.2">
<b>Exercise 2.2</b><br>
Write four different C++ statements that each add 1 to integer variable <b>x</b>.<br>
<foreign name="answers" url="^Answers::c:s0p1">
</page>
<page pagename="Exercise 2.3">
<b>Exercise 2.3</b><br>
Write C++ statements to accomplish each of the following:<br>
a) Assign the sum of <b>x</b> and <b>y</b> to <b>z</b> and increment the value of <b>x</b> by <b>1</b> after the
calculation.<br>
b) Test if the value of the variable count is greater than 10. If it is, print
"<b>Count is greater than 10.</b>"<br>
c) Decrement the variable <b>x</b> by <b>1</b> then subtract it from the variable <b>total</b>.<br>
d) Calculate the remainder after <b>q</b> is divided by <b>divisor</b> and assign the result to
<b>q</b>. Write this statement two different ways.<br>
<foreign name="answers" url="^Answers::c:s0p2">
</page>
<page pagename="Exercise 2.4">
<b>Exercise 2.4</b><br>
Write a C++ statement to accomplish each of the following tasks.<br>
a) Declare variables <b>sum</b> and <b>x</b> to be of type <b>int</b>.<br>
b) Initialize variable <b>x</b> to <b>1</b>.<br>
c) Initialize variable <b>sum</b> to <b>0</b>.<br>
d) Add variable<b> x</b> to variable <b>sum</b> and assign the result to variable <b>sum</b>.<br>
e) Print "<b>The sum is:</b> " followed by the value of variable <b>sum</b>.<br>
<foreign name="answers" url="^Answers::c:s0p3">
</page>
<page pagename="Exercise 2.5">
<b>Exercise 2.5</b><br>
Combine the statements that you wrote in<a href="^Exercises::c:s0p4"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 2.4</a> into a program that
calculates and prints the sum of the integers from 1 to 10. Use the <b>while</b>
structure to loop through the calculation and increment statements. The loop
should terminate when the value of <b>x</b> becomes <b>11</b>.<br>
<foreign name="answers" url="^Answers::c:s0p4">
</page>
<page pagename="Exercise 2.6">
<b>Exercise 2.6</b><br>
Determine the values of each variable after the calculation is performed. Assume
that when each statement begins executing all variables have the integer value 5.<br>
<font size=2><br></font><font size=11><pre>
a) product *= x++;<p>
b) quotient /= ++x;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p6">
</page>
<page pagename="Exercise 2.7">
<b>Exercise 2.7</b><br>
Write single C++ statements that<br>
a) Input integer variable <b>x</b> with <b>cin</b> and <b>>></b>.<br>
b) Input integer variable <b>y</b> with <b>cin</b> and <b>>></b>.<br>
c) Initialize integer variable <b>i</b> to <b>1</b>.<br>
d) Initialize integer variable <b>power</b> to <b>1</b>.<br>
e) Multiply variable <b>power</b> by <b>x</b> and assign the result to <b>power</b>.<br>
f) Increment variable <b>y</b> by <b>1</b>.<br>
g) Test <b>y</b> to see if it is less than or equal to<b> x</b>.<br>
h) Output integer variable <b>power</b> with <b>cout</b> and <b><<</b>.<br>
<foreign name="answers" url="^Answers::c:s0p7">
</page>
<page pagename="Exercise 2.8">
<b>Exercise 2.8</b><br>
Write a C++ program that uses the statements in <a href="^Exercises::c:s0p7"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 2.7</a> to calculate<b> x</b>
raised to the <b>y</b> power. The program should have a <b>while</b> repetition control
structure.<br>
<foreign name="answers" url="^Answers::c:s0p8">
</page>
<page pagename="Exercise 2.9">
<b>Exercise 2.9</b><br>
Identify and correct the errors in each of the following:<br>
<font size=2><br></font><font size=11><pre>
a) while ( c <= 5 ) {<p>
product *= c;<p>
++c;<p>
b) cin << value;<p>
c) if ( gender == 1 )<p>
cout << "Woman" << endl;<p>
else;<p>
cout << "Man" << endl;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p10">
</page>
<page pagename="Exercise 2.10">
<b>Exercise 2.10</b><br>
What is wrong with the following <b>while</b> repetition structure:<br>
<font size=2><br></font><font size=11><pre>
while ( z >= 0 )<p>
sum += z;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p11">
</page>
<page pagename="Exercise 2.11">
<b>Exercise 2.11</b><br>
State whether the following are true or false. If the answer is false, explain why.<br>
a) The <b>default</b> case is required in the <b>switch</b> selection structure.<br>
b) The <b>break</b> statement is required in the default case of a <b>switch</b> selection
structure to exit the structure properly.<br>
c) The expression <b>( x > y && a < b )</b> is <b>true</b> if either the expression <b>x > y</b> is
<b>true</b> or the expression <b>a < b</b> is <b>true</b>.<br>
d) An expression containing the <b>||</b> operator is <b>true</b> if either or both of its
operands is <b>true</b>.<br>
<foreign name="answers" url="^Answers::c:s0p12">
</page>
<page pagename="Exercise 2.12">
<b>Exercise 2.12</b><br>
Write a C++ statement or a set of C++ statements to accomplish each of the
following:<br>
a) Sum the odd integers between 1 and 99 using a <b>for</b> structure. Assume the
integer variables <b>sum</b> and <b>count</b> have been declared. <br>
b) Print the value <b>333.546372</b> in a field width of <b>15</b> characters with precisions
of <b>1</b>, <b>2</b>, and <b>3</b>. Print each number on the same line. Left justify each number in its
field. What three values print?<br>
c) Calculate the value of <b>2.5</b> raised to the power of <b>3</b> using the <b>pow</b> function.
Print the result with a precision of <b>2</b> in a field width of <b>10</b> positions. What
prints?<br>
<foreign name="answers" url="^Answers::c:s0p13">
</page>
<page pagename="Exercise 2.12">
d) Print the integers from 1 to 20 using a <b>while</b> loop and the counter variable <b>x</b>.
Assume that the variable <b>x</b> has been declared, but not initialized. Print only 5
integers per line. Hint: Use the calculation <b>x % 5</b>. When the value of this is 0,
print a newline character, otherwise print a tab character.<br>
e) Repeat Exercise 2.12 (d) using a <b>for</b> structure.<br>
<foreign name="answers" url="^Answers::c:s0p13">
</page>
<page pagename="Exercise 2.13">
<b>Exercise 2.13</b><br>
Find the error in each of the following code segments and explain how to correct
it.<br>
<font size=2><br></font><font size=11><pre>
a) x = 1;<p>
while ( x <= 10 );<p>
x++;<p>
}<p>
b) for ( y = .1; y != 1.0; y += .1 )<p>
cout << y << endl;<p>
c) switch ( n ) {<p>
case 1:<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p17">
</page>
<page pagename="Exercise 2.13">
<font size=2><br></font><font size=11><pre>
cout << "The number is 1" << endl;<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
case 2:<p>
cout << "The number is 2" << endl;<p>
break;<p>
default:<p>
cout << "The number is not 1 or 2" << endl;<p>
break;<p>
}<p>
</pre></font>
d) The following code should print the values 1 to 10.<br>
<font size=2><br></font><font size=11><pre>
n = 1;<p>
while ( n < 10 ) <p>
cout << n++ << endl;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p17">
</page>
<page pagename="Exercise 2.14">
<b>Exercise 2.14</b><br>
Exercises 2.14 through 2.38 correspond to Sections 2.1 through 2.12.<p>
Exercises 2.39 through 2.63 correspond to Sections 2.13 through 2.21.<br>
<br>
Identify and correct the errors in each of the following (Note: There may be
more than one error in each piece of code):<br>
<font size=2><br></font><font size=11><pre>
a) if ( age >= 65 );<p>
cout << "Age is greater than or equal to 65" << endl;<p>
else<p>
cout << "Age is less than 65 << endl";<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p19">
</page>
<page pagename="Exercise 2.14">
<font size=2><br></font><font size=11><pre>
b) if ( age >= 65 )<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
cout << "Age is greater than or equal to 65" << endl;<p>
else;<p>
cout << "Age is less than 65 << endl";<p>
c) int x = 1, total;<p>
while ( x <= 10 ) {<p>
total += x;<p>
++x;<p>
}<p>
d) While ( x <= 100 )<p>
total += x;<p>
++x;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p19">
</page>
<page pagename="Exercise 2.14">
<font size=2><br></font><font size=11><pre>
e) while ( y > 0 ) {<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
cout << y << endl;<p>
++y;<p>
}<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p19">
<br>
</page>
<page pagename="Exercise 2.15">
<b>Exercise 2.15</b><br>
What does the following program print?<br>
<font size=2><br></font><font size=11><pre>
#include <iostream.h><p>
int main()<p>
{<p>
int y, x = 1, total = 0;<p>
while (x <= 10) {<p>
y = x * x;<p>
cout << y << endl;<p>
total += y;<p>
++x;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.15">
<font size=2><br></font><font size=11><pre>
cout << "Total is " << total << endl;<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
return 0;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.15">
<font size=18>For Exercises 2.16 to 2.19 perform each of these steps:</font><br>
a) Read the problem statement.<br>
b) Formulate the algorithm using pseudocode and top-down, stepwise
refinement.<br>
c) Write a C++ program.<br>
d) Test, debug, and execute the C++ program.<br>
<br>
</page>
<page pagename="Exercise 2.16">
<b>Exercise 2.16</b><br>
Drivers are concerned with the mileage obtained by their automobiles. One
driver has kept track of several tankfuls of gasoline by recording miles driven
and gallons used for each tankful. Develop a C++ program that will input the
miles driven and gallons used for each tankful. The program should calculate
and display the miles per gallon obtained for each tankful. After processing all
input information, the program should calculate and print the combined miles
per gallon obtained for all tankfuls.<br>
<hr>
<font size=2><br></font><font size=11><pre>
Enter the gallons used (-1 to end): 12.8<p>
Enter the miles driven: 287<p>
The miles / gallon for this tank was 22.421875<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p23">
</page>
<page pagename="Exercise 2.16">
<font size=2><br></font><font size=11><pre>
Enter the gallons used (-1 to end): 10.3<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
Enter the miles driven: 200<p>
The miles / gallon for this tank was 19.417475<p>
<p>
Enter the gallons used (-1 to end): 5<p>
Enter the miles driven: 120<p>
The miles / gallon for this tank was 24.000000<p>
<p>
Enter the gallons used (-1 to end): -1<p>
<p>
The overall average miles/gallon was 21.601423<p>
</pre></font>
<hr>
<foreign name="answers" url="^Answers::c:s0p23">
</page>
<page pagename="Exercise 2.17">
<b>Exercise 2.17</b><br>
Develop a C++ program that will determine if a department store customer has
exceeded the credit limit on a charge account. For each customer, the following
facts are available:<br>
a) Account number (an integer)<br>
b) Balance at the beginning of the month<br>
c) Total of all items charged by this customer this month<br>
d) Total of all credits applied to this customer's account this month<br>
e) Allowed credit limit<br>
The program should input each of these facts, calculate the new balance (=
beginning balance + charges - credits), and determine if the new balance exceeds
the customer's credit limit. For those customers whose credit limit is exceeded, <br>
</page>
<page pagename="Exercise 2.17">
the program should display the customer's account number, credit limit, new
balance, and the message "Credit limit exceeded."<br>
<hr>
<font size=2><br></font><font size=11><pre>
Enter account number (-1 to end): 100<p>
Enter beginning balance: 5394.78<p>
Enter total charges: 1000.00<p>
Enter total credits: 500.00<p>
Enter credit limit: 5500.00<p>
Account: 100<p>
Credit limit: 5500.00<p>
Balance: 5894.78<p>
Credit Limit Exceeded.<p>
<p>
</pre></font>
</page>
<page pagename="Exercise 2.17">
<font size=2><br></font><font size=11><pre>
Enter account number (-1 to end): 200<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
Enter beginning balance: 1000.00<p>
Enter total charges: 123.45<p>
Enter total credits: 321.00<p>
Enter credit limit: 1500.00<p>
<p>
Enter account number (-1 to end): 300<p>
Enter beginning balance: 500.00<p>
Enter total charges: 274.73<p>
Enter total credits: 100.00<p>
Enter credit limit: 800.00<p>
<p>
Enter account number (-1 to end): -1<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.18">
<b>Exercise 2.18</b><br>
One large chemical company pays its salespeople on a commission basis. The
salespeople receive $200 per week plus 9 percent of their gross sales for that
week. For example, a salesperson who sells $5000 worth of chemicals in a week
receives $200 plus 9 percent of $5000, or a total of $650. Develop a C++
program that will input each salesperson's gross sales for last week and calculate
and display that salesperson's earnings. Process one salesperson's figures at a
time.<br>
<hr>
<font size=2><br></font><font size=11><pre>
Enter sales in dollars (-1 to end): 5000.00<p>
Salary is: $650.00<p>
<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p24">
</page>
<page pagename="Exercise 2.18">
<font size=2><br></font><font size=11><pre>
Enter sales in dollars (-1 to end): 6000.00<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
Salary is: $740.00<p>
<p>
Enter sales in dollars (-1 to end): 7000.00<p>
Salary is: $830.00<p>
<p>
Enter sales in dollars (-1 to end): -1<p>
</pre></font>
<hr>
<foreign name="answers" url="^Answers::c:s0p24">
<br>
</page>
<page pagename="Exercise 2.19">
<b>Exercise 2.19</b><br>
Develop a C++ program that will determine the gross pay for each of several
employees. The company pays "straight-time" for the first 40 hours worked by
each employee and pays "time-and-a-half" for all hours worked in excess of 40
hours. You are given a list of the employees of the company, the number of
hours each employee worked last week, and the hourly rate of each employee.
Your program should input this information for each employee, and should
determine and display the employee's gross pay.<br>
<hr>
<font size=2><br></font><font size=11><pre>
Enter hours worked (-1 to end): 39<p>
Enter hourly rate of the worker ($00.00): 10.00<p>
Salary is $390.00<p>
<p>
</pre></font>
</page>
<page pagename="Exercise 2.19">
<font size=2><br></font><font size=11><pre>
Enter hours worked (-1 to end): 40<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
Enter hourly rate of the worker ($00.00): 10.00<p>
Salary is $400.00<p>
<p>
Enter hours worked (-1 to end): 41<p>
Enter hourly rate of the worker ($00.00): 10.00<p>
Salary is $415.00<p>
<p>
Enter hours worked (-1 to end): -1<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.20">
<b>Exercise 2.20</b><br>
The process of finding the largest number (i.e., the maximum of a group of
numbers) is used frequently in computer applications. For example, a program
that determines the winner of a sales contest would input the number of units
sold by each salesperson. The salesperson who sells the most units wins the
contest. Write a pseudocode program and then a C++ program that inputs a
series of 10 numbers, and determines and prints the largest of the numbers. Hint:
Your program should use three variables as follows:<br>
<b>counter:</b> A counter to count to 10 (i.e., to keep track of how many numbers
have been input, and to determine when all 10 numbers have been processed).<br>
<b>number:</b> The current number input to the program.<br>
<b>largest:</b> The largest number found so far.<br>
<foreign name="answers" url="^Answers::c:s0p25">
</page>
<page pagename="Exercise 2.21">
<b>Exercise 2.21</b><br>
Write a C++ program that utilizes looping and the tab escape sequence <b>\ </b> to print
the following table of values:<br>
<hr>
<font size=2><br></font><font size=11><pre>
N 10*N 100*N 1000*N<spacer width=20 height=1> <p>
<p>
1 10 100 1000<p>
2 20 200 2000<p>
3 30 300 3000<p>
4 40 400 4000<p>
5 50 500 5000<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.22">
<b>Exercise 2.22</b><br>
Using an approach similar to<a href="^Exercises::c:s0p31"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 2.20</a>, find the <i>two</i> largest values of the 10
numbers. Note: You may input each number only once.<br>
</page>
<page pagename="Exercise 2.23">
<b>Exercise 2.23</b><br>
Modify the program in <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.11</a> to validate its inputs. On any input, if the value
entered is other than 1 or 2, keep looping until the user enters a correct value.<br>
</page>
<page pagename="Exercise 2.24">
<b>Exercise 2.24</b><br>
What does the following program print?<br>
<font size=2><br></font><font size=11><pre>
#include <iostream.h><p>
int main()<p>
{<p>
int count = 1;<p>
while ( count <= 10 ) {<p>
cout << ( count % 2 ? "****" : "++++++++" )<p>
<< endl;<p>
++count;<p>
}<p>
return 0;<p>
}<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p20">
</page>
<page pagename="Exercise 2.25">
<b>Exercise 2.25</b><br>
What does the following program print?<br>
<font size=2><br></font><font size=11><pre>
#include <iostream.h><p>
int main()<p>
{<p>
int row = 10, column;<p>
while ( row >= 1 ) {<p>
column = 1;<p>
while ( column <= 10 ) {<p>
cout << ( row % 2 ? "<" : ">" );<p>
++column;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.25">
<font size=2><br></font><font size=11><pre>
--row;<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
cout << endl;<p>
}<p>
return 0;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.26">
<b>Exercise 2.26</b><br>
(<i>Dangling Else Problem</i>) Determine the output for each of the following when <b>x</b>
is <b>9</b> and <b>y</b> is <b>11</b> and when <b>x</b> is <b>11</b> and <b>y</b> is <b>9</b>. Note that the compiler ignores the
indentation in a C++ program. Also, the C++ compiler always associates an <b>else</b>
with the previous <b>if</b> unless told to do otherwise by the placement of braces <b>{}</b>.
Because, on first glance, the programmer may not be sure which <b>if</b> an else
matches, this is referred to as the "dangling else" problem. We have eliminated
the indentation from the following code to make the problem more challenging.
(Hint: Apply indentation conventions you have learned.)<br>
<font size=2><br></font><font size=11><pre>
a) if ( x < 10 )<p>
if ( y > 10 )<p>
cout << "*****" << endl;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p21">
</page>
<page pagename="Exercise 2.26">
<font size=2><br></font><font size=11><pre>
else<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
cout << "#####" << endl;<p>
cout << "$$$$$" << endl;<p>
b) if ( x < 10 ) {<p>
if ( y > 10 )<p>
cout << "*****" << endl; <p>
}<p>
else {<p>
cout << "#####" << endl;<p>
cout << "$$$$$" << endl;<p>
}<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p21">
</page>
<page pagename="Exercise 2.27">
<b>Exercise 2.27</b><br>
(<i>Another Dangling Else Problem</i>) Modify the following code to produce the
output shown. Use proper indentation techniques. You may not make any
changes other than inserting braces. The compiler ignores indentation in a C++
program. We have eliminated the indentation from the following code to make
the problem more challenging. Note: It is possible that no modification is
necessary.<br>
<font size=2><br></font><font size=11><pre>
if ( y == 8 )<p>
if ( x == 5 )<p>
cout << "@@@@@" << endl;<p>
else<p>
cout << "#####" << endl;<p>
</pre></font>
</page>
<page pagename="Exercise 2.27">
<font size=2><br></font><font size=11><pre>
cout << "$$$$$" << endl;<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
cout << "&&&&&" << endl;<p>
</pre></font>
a) Assuming <b>x = 5</b> and <b>y = 8</b>, the following output is produced.<br>
<hr>
<font size=2><br></font><font size=11><pre>
@@@@@<p>
$$$$$<p>
&&&&&<p>
</pre></font>
<hr>
b) Assuming <b>x = 5</b> and <b>y = 8</b>, the following output is produced.<br>
<hr>
<font size=2><br></font><font size=11><pre>
@@@@@<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.27">
c) Assuming <b>x = 5</b> and <b>y = 8</b>, the following output is produced.<br>
<hr>
<font size=2><br></font><font size=11><pre>
@@@@@<p>
&&&&&<p>
</pre></font>
<hr>
d) Assuming <b>x = 5</b> and <b>y = 7</b>, the following output is produced. Note: The last
three output statements after the else are all part of a compound statement.<br>
<hr>
<font size=2><br></font><font size=11><pre>
#####<p>
$$$$$<p>
&&&&&<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.28">
<b>Exercise 2.28</b><br>
Write a program that reads in the size of the side of a square and then prints a
hollow square of that size out of asterisks and blanks. Your program should
work for squares of all side sizes between 1 and 20. For example, if your
program reads a size of 5, it should print<br>
<hr>
<font size=2><br></font><font size=11><pre>
*****<p>
* *<p>
* *<p>
* *<p>
*****<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.29">
<b>Exercise 2.29</b><br>
A palindrome is a number or a text phrase that reads the same backwards as
forwards. For example, each of the following five-digit integers are
palindromes: 12321, 55555, 45554 and 11611. Write a program that reads in a
five-digit integer and determines whether or not it is a palindrome. (Hint: Use
the division and modulus operators to separate the number into its individual
digits.)<br>
<foreign name="answers" url="^Answers::c:s0p26">
<br>
</page>
<page pagename="Exercise 2.30">
<b>Exercise 2.30</b><br>
Input an integer containing only 0s and 1s (i.e., a "binary" integer) and print its
decimal equivalent. (Hint: Use the modulus and division operators to pick off
the "binary" number's digits one at a time from right to left. Just as in the
decimal number system where the rightmost digit has a positional value of 1,
and the next digit left has a positional value of 10, then 100, then 1000, etc., in
the binary number system the rightmost digit has a positional value of 1, the next
digit left has a positional value of 2, then 4, then 8, etc. Thus the decimal number
234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of
binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.)<br>
</page>
<page pagename="Exercise 2.31">
<b>Exercise 2.31</b><br>
Write a program that displays the following checkerboard pattern<br>
<hr>
<font size=2><br></font><font size=11><pre>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
* * * * * * * *<p>
</pre></font>
<hr>
<foreign name="answers" url="^Answers::c:s0p27">
</page>
<page pagename="Exercise 2.31">
Your program may use only three output statements, one of each of the
following forms:<br>
<font size=2><br></font><font size=11><pre>
cout << "* "; <p>
cout << ' ';<p>
cout << endl;<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p27">
<br>
</page>
<page pagename="Exercise 2.32">
<b>Exercise 2.32</b><br>
Write a program that keeps printing the multiples of the integer 2, namely 2, 4, 8,
16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite
loop). What happens when you run this program? <br>
</page>
<page pagename="Exercise 2.33">
<b>Exercise 2.33</b><br>
Write a program that reads the radius of a circle (as a <b>float</b> value) and computes
and prints the diameter, the circumference, and the area. Use the value 3.14159
for <i>pi</i>.<br>
<foreign name="answers" url="^Answers::c:s0p28">
<br>
</page>
<page pagename="Exercise 2.34">
<b>Exercise 2.34</b><br>
What's wrong with the following statement? Provide the correct statement to
accomplish what the programmer was probably trying to do.<br>
<font size=2><br></font><font size=11><pre>
cout << ++( x + y );<p>
</pre></font>
</page>
<page pagename="Exercise 2.35">
<b>Exercise 2.35</b><br>
Write a program that reads three nonzero <b>float</b> values and determines and prints
if they could represent the sides of a triangle.<br>
</page>
<page pagename="Exercise 2.36">
<b>Exercise 2.36</b><br>
Write a program that reads three nonzero integers and determines and prints if
they could be the sides of a right triangle.<br>
</page>
<page pagename="Exercise 2.37">
<b>Exercise 2.37</b><br>
A company wants to transmit data over the telephone, but they are concerned
that their phones may be tapped. All of their data is transmitted as four-digit
integers. They have asked you to write a program that encrypts their data so that
it may be transmitted more securely. Your program should read a four-digit
integer and encrypt it as follows: Replace each digit by (<i>the sum of that digit
plus 7</i>) <i>modulus 10</i>. Then, swap the first digit with the third, swap the second
digit with the fourth, and print the encrypted integer. Write a separate program
that inputs an encrypted four-digit integer, and decrypts it to form the original
number.<br>
<foreign name="answers" url="^Answers::c:s0p29">
<br>
</page>
<page pagename="Exercise 2.38">
<b>Exercise 2.38</b><br>
The factorial of a nonnegative integer <i>n</i> is written n! (pronounced "<i>n</i> factorial")
and is defined as follows:<br>
<i>n</i>! = <i>n</i> x (<i>n</i> - 1) x (<i>n </i>- 2) x ... x 1 (for values of <i>n</i> greater than or equal to 1)<br>
and<br>
<i>n</i>! = 1 (for <i>n </i>= 0).<br>
For example, 5! = 5 x 4 x 3 x 2 x 1 which is 120. <br>
a) Write a program that reads a nonnegative integer and computes and prints its
factorial.<br>
b) Write a program that estimates the value of the mathematical constant <i>e</i> by
using the formula: <br>
</page>
<page pagename="Exercise 2.38">
<img src="graphics/ch02/ex0238a.gif" ><br>
c) Write a program that computes the value of <img src="graphics/ch02/ex0238b.gif" > by using the formula <br>
<font size=2><br></font><font size=11><pre>
<img src="graphics/ch02/ex0238c.gif" ><p>
</pre></font>
</page>
<page pagename="Exercise 2.39">
<b>Exercise 2.39</b><br>
Find the error in each of the following (Note: There may be more than one
error):<br>
<font size=2><br></font><font size=11><pre>
a) For ( x = 100, x >= 1, x++ )<p>
cout << x << endl;<p>
</pre></font>
b) The following code should print whether integer <b>value</b> is odd or even:<br>
<font size=2><br></font><font size=11><pre>
switch ( value % 2 ) {<p>
case 0:<p>
cout << "Even integer" << endl;<p>
case 1:<p>
cout << "Odd integer" << endl;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.39">
c) The following code should output the odd integers from 19 to 1:<br>
<font size=2><br></font><font size=11><pre>
for ( x = 19; x >= 1; x += 2 )<p>
cout << x << endl;<p>
</pre></font>
d) The following code should output the even integers from 2 to 100:<br>
<font size=2><br></font><font size=11><pre>
counter = 2;<p>
do {<p>
cout << counter << endl;<p>
counter += 2;<p>
} While ( counter < 100 );<p>
</pre></font>
<br>
</page>
<page pagename="Exercise 2.40">
<b>Exercise 2.40</b><br>
Write a program that sums a sequence of integers. Assume that the first integer
read specifies the number of values remaining to be entered. Your program
should read only one value per input statement. A typical input sequence might
be <br>
<font size=2><br></font><font size=11><pre>
5 100 200 300 400 500<p>
</pre></font>
where the <b>5</b> indicates that the subsequent <b>5</b> values are to be summed.<br>
<foreign name="answers" url="^Answers::c:s0p30">
<br>
</page>
<page pagename="Exercise 2.41">
<b>Exercise 2.41</b><br>
Write a program that calculates and prints the average of several integers.
Assume the last value read is the sentinel <b>9999</b>. A typical input sequence might
be<br>
<font size=2><br></font><font size=11><pre>
10 8 11 7 9 9999<p>
</pre></font>
indicating that the average of all the values preceding <b>9999</b> is to be calculated.<br>
<br>
<br>
</page>
<page pagename="Exercise 2.42">
<b>Exercise 2.42</b><br>
What does the following program do?<br>
<font size=2><br></font><font size=11><pre>
#include <iostream.h><p>
int main()<p>
{<p>
int x, y;<p>
cout << "Enter two integers in the range 1-20: ";<p>
cin >> x >> y;<p>
for ( int i = 1; i <= y; i++ ) {<p>
for ( int j = 1; j <= x; j++ )<p>
cout << '@';<p>
cout << endl;<p>
</pre></font>
</page>
<page pagename="Exercise 2.42">
<font size=2><br></font><font size=11><pre>
}<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
return 0;<p>
}<p>
</pre></font>
<br>
<br>
</page>
<page pagename="Exercise 2.43">
<b>Exercise 2.43</b><br>
Write a program that finds the smallest of several integers. Assume that the first
value read specifies the number of values remaining.<br>
<br>
<foreign name="answers" url="^Answers::c:s0p31">
<br>
</page>
<page pagename="Exercise 2.44">
<b>Exercise 2.44</b><br>
Write a program that calculates and prints the product of the odd integers from 1
to 15.<br>
<br>
<br>
</page>
<page pagename="Exercise 2.45">
<b>Exercise 2.45</b><br>
The <i>factorial</i> function is used frequently in probability problems. The factorial
of a positive integer <i>n</i> (written <i>n!</i> and pronounced "n factorial") is equal to the
product of the positive integers from 1 to <i>n</i>. Write a program that evaluates the
factorials of the integers from 1 to 5. Print the results in tabular format. What
difficulty might prevent you from calculating the factorial of 20?<br>
<br>
<foreign name="answers" url="^Answers::c:s0p32">
<br>
</page>
<page pagename="Exercise 2.46">
<b>Exercise 2.46</b><br>
Modify the compound interest program of<a href="^Illustration::c:s0p13"> Section 2.15</a> to repeat its steps for
interest rates of 5 percent, 6 percent, 7 percent, 8 percent, 9 percent, and 10
percent. Use a <b>for</b> loop to vary the interest rate.<br>
<br>
</page>
<page pagename="Exercise 2.47">
<b>Exercise 2.47</b><br>
Write a program that prints the following patterns separately one below the
other. Use <b>for</b> loops to generate the patterns. All asterisks (<b>*</b>) should be printed
by a single statement of the form <b>cout << '*';</b> (this causes the asterisks to print
side by side). Hint: The last two patterns require that each line begin with an
appropriate number of blanks. Extra credit: Combine your code from the four
separate problems into a single program that prints all four patterns side by side
making clever use of nested <b>for</b> loops.<br>
</page>
<page pagename="Exercise 2.47">
<hr>
<font size=2><br></font><font size=11><pre>
(A) (B) (C) (D)<p>
* ********** ********** *<p>
** ********* ********* **<p>
*** ******** ******** ***<p>
**** ******* ******* ****<p>
***** ****** ****** *****<p>
****** ***** ***** ******<p>
******* **** **** *******<p>
******** *** *** ********<p>
********* ** ** *********<p>
********** * * **********<p>
</pre></font>
<hr>
</page>
<page pagename="Exercise 2.48">
<b>Exercise 2.48</b><br>
One interesting application of computers is drawing graphs and bar charts
(sometimes called "histograms"). Write a program that reads five numbers (each
between 1 and 30). For each number read, your program should print a line
containing that number of adjacent asterisks. For example, if your program reads
the number seven, it should print <b>*******</b>.<br>
<br>
<foreign name="answers" url="^Answers::c:s0p33">
<br>
</page>
<page pagename="Exercise 2.49">
<b>Exercise 2.49</b><br>
A mail order house sells five different products whose retail prices are product 1
-- $2.98, product 2--$4.50, product 3--$9.98, product 4--$4.49, and product
5--$6.87. Write a program that reads a series of pairs of numbers as follows:<br>
a) Product number<br>
b) Quantity sold for one day<br>
Your program should use a <b>switch</b> statement to help determine the retail price
for each product. Your program should calculate and display the total retail
value of all products sold last week.<br>
<br>
<foreign name="answers" url="^Answers::c:s0p34">
<br>
</page>
<page pagename="Exercise 2.50">
<b>Exercise 2.50</b><br>
Modify the program of<a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.22</a> so that it calculates the grade point average for
the class. A grade of 'A' is worth 4 points, 'B' is worth 3 points, etc.<br>
<br>
<br>
</page>
<page pagename="Exercise 2.51">
<b>Exercise 2.51</b><br>
Modify the program in <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.21</a> so it uses only integers to calculate the
compound interest. (Hint: Treat all monetary amounts as integral numbers of
pennies. Then "break" the result into its dollar portion and cents portion by using
the division and modulus operations. Insert a period.)<br>
<br>
<br>
</page>
<page pagename="Exercise 2.52">
<b>Exercise 2.52</b><br>
Assume <b>i = 1</b>, j = 2, <b>k = 3</b>, and <b>m = 2</b>. What does each of the following
statements print? Are the parentheses necessary in each case?<br>
<font size=2><br></font><font size=11><pre>
a) cout << ( i == 1 ) << endl;<p>
b) cout << ( j == 3 ) << endl;<p>
c) cout << ( i >= 1 && j < 4 ) << endl;<p>
d) cout << ( m <= 99 && k < m ) << endl;<p>
e) cout << ( j >= i || k == m ) << endl;<p>
f) cout << ( k + m < j || 3 - j >= k ) << endl;<p>
g) cout << ( !m ) << endl;<p>
h) cout << ( !( j - m ) ) << endl;<p>
i) cout << ( !( k > m ) ) << endl;<p>
</pre></font>
</page>
<page pagename="Exercise 2.53">
<b>Exercise 2.53</b><br>
Write a program that prints a table of the binary, octal, and hexadecimal
equivalents of the decimal numbers in the range 1 through 256. If you are not
familiar with these number systems, read Appendix E first. <br>
<br>
<br>
</page>
<page pagename="Exercise 2.54">
<b>Exercise 2.54</b><br>
Calculate the value of <i>pi</i> from the infinite series <br>
<font size=2><br></font><font size=11><pre>
<img src="graphics/ch02/ex0254a.gif" ><p>
</pre></font>
Print a table that shows the value of <i>pi</i> approximated by 1 term of this series, by
two terms, by three terms, etc. How many terms of this series do you have to use
before you first get 3.14? 3.141? 3.1415? 3.14159?<br>
<foreign name="answers" url="^Answers::c:s0p35">
<br>
</page>
<page pagename="Exercise 2.55">
<b>Exercise 2.55</b><br>
(<i>Pythagorean Triples</i>) A right triangle can have sides that are all integers. The
set of three integer values for the sides of a right triangle is called a Pythagorean
triple. These three sides must satisfy the relationship that the sum of the squares
of two of the sides is equal to the square of the hypotenuse. Find all Pythagorean
triples for <b>side1</b>, <b>side2</b>, and the <b>hypotenuse</b> all no larger than 500. Use a triple-
nested <b>for</b>-loop that tries all possibilities. This is an example of "brute force"
computing. You will learn in more advanced computer science courses that there
are many interesting problems for which there is no known algorithmic
approach other than using sheer brute force. <br>
</page>
<page pagename="Exercise 2.56">
<b>Exercise 2.56</b><br>
A company pays its employees as managers (who receive a fixed weekly salary),
hourly workers (who receive a fixed hourly wage for up to the first 40 hours they
work and "time-and-a-half," i.e., 1.5 times their hourly wage, for overtime hours
worked), commission workers (who receive $250 plus 5.7% of their gross
weekly sales), or pieceworkers (who receive a fixed amount of money per item
for each of the items they produce--each pieceworker in this company works on
only one type of item). Write a program to compute the weekly pay for each
employee. You do not know the number of employees in advance. Each type of
employee has its own pay code: Managers have paycode 1, hourly workers have
code 2, commission workers have code 3 and pieceworkers have code 4. Use a
<b>switch</b> to compute each employee's pay based on that employee's paycode. <br>
</page>
<page pagename="Exercise 2.56">
Within the <b>switch</b>, prompt the user (i.e., the payroll clerk) to enter the
appropriate facts your program needs to calculate each employee's pay based on
that employee's paycode.<br>
</page>
<page pagename="Exercise 2.57">
<b>Exercise 2.57</b><br>
(<i>De Morgan's Laws</i>) In this chapter, we discussed the logical operators <b>&&</b>, <b>||</b>,
and <b>!</b>. De Morgan's Laws can sometimes make it more convenient for us to
express a logical expression. These laws state that the expression <b>!</b>(<i>condition1</i>
<b>&&</b> <i>condition2</i>) is logically equivalent to the expression (<b>!</b><i>condition1</i> <b>||</b>
!condition2). Also, the expression <b>!(<i>condition1 || condition2)</i></b> is logically
equivalent to the expression (<b>!</b><i>condition1<b> && !</b>condition2</i>). Use De Morgan's
Laws to write equivalent expressions for each of the following, and then write a
program to show that both the original expression and the new expression in
each case are equivalent:<br>
<font size=2><br></font><font size=11><pre>
a) !( x < 5 ) && !( y >= 7 )<p>
b) !( a == b ) || !( g != 5 )<p>
</pre></font>
</page>
<page pagename="Exercise 2.57">
<font size=2><br></font><font size=11><pre>
c) !( ( x <= 8 ) && ( y > 4 ) )<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
d) !( ( i > 4 ) || ( j <= 6 ) )<p>
</pre></font>
</page>
<page pagename="Exercise 2.58">
<b>Exercise 2.58</b><br>
Write a program that prints the following diamond shape. You may use output
statements that print either a single asterisk (<b>*</b>) or a single blank. Maximize your
use of repetition (with nested <b>for</b> structures) and minimize the number of output
statements.<br>
<hr>
<font size=2><br></font><font size=11><pre>
*<p>
***<p>
*****<p>
*******<p>
*********<p>
*******<p>
</pre></font>
<foreign name="answers" url="^Answers::c:s0p36">
</page>
<page pagename="Exercise 2.58">
<font size=2><br></font><font size=11><pre>
*****<p>
</pre></font>
<font size=2><br></font><font size=11><pre>
***<p>
*<p>
</pre></font>
<hr>
<foreign name="answers" url="^Answers::c:s0p36">
<br>
</page>
<page pagename="Exercise 2.59">
<b>Exercise 2.59</b><br>
Modify the program you wrote in <a href="^Exercises::c:s0p80"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 2.58</a> to read an odd number in the
range 1 to 19 to specify the number of rows in the diamond. Your program
should then display a diamond of the appropriate size.<br>
<br>
<br>
</page>
<page pagename="Exercise 2.60">
<b>Exercise 2.60</b><br>
A criticism of the <b>break</b> statement and the <b>continue</b> statement is that each is
unstructured. Actually <b>break</b> statements and <b>continue</b> statements can always be
replaced by structured statements, although doing so can be awkward. Describe
in general how you would remove any <b>break</b> statement from a loop in a
program and replace that statement with some structured equivalent. (Hint: The
<b>break</b> statement leaves a loop from within the body of the loop. The other way
to leave is by failing the loop-continuation test. Consider using in the loop-
continuation test a second test that indicates "early exit because of a 'break'
condition.") Use the technique you developed here to remove the break
statement from the program of <a href="^Code::c:s0p10"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.26</a>.<br>
<foreign name="answers" url="^Answers::c:s0p37">
</page>
<page pagename="Exercise 2.61">
<b>Exercise 2.61</b><br>
What does the following program segment do?<br>
<font size=2><br></font><font size=11><pre>
for ( i = 1; i <= 5; i++ ) {<p>
for ( j = 1; j <= 3; j++ ) {<p>
for ( k = 1; k <= 4; k++ )<p>
cout << '*';<p>
cout << endl;<p>
}<p>
cout << endl;<p>
}<p>
</pre></font>
</page>
<page pagename="Exercise 2.62">
<b>Exercise 2.62</b><br>
Describe in general how you would remove any <b>continue</b> statement from a loop
in a program and replace that statement with some structured equivalent. Use the
technique you developed here to remove the <b>continue</b> statement from the
program of <a href="^Code::c:s0p11"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.27</a>. <br>
</page>
<page pagename="Exercise 2.63">
<b>Exercise 2.63</b><br>
(<i>"The Twelve Days of Christmas" Song</i>) Write a program that uses repetition
and <b>switch</b> structures to print the song "The Twelve Days of Christmas." One
<b>switch</b> structure should be used to print the day (i.e., "First," "Second," etc.). A
separate <b>switch</b> structure should be used to print the remainder of each verse.<br>
<foreign name="answers" url="^Answers::c:s0p38">
<br>
</page>
<page pagename="Exercise 2.64">
<b>Exercise 2.64</b><br>
Exercise 2.64 corresponds to<a href="#s22p0"> Section 2.22</a>, "Thinking About Objects."<br>
<br>
Describe in 200 words or less what an automobile is and does. List the nouns
and verbs separately. In the text, we stated that each noun may correspond to an
object that will need to be built to implement a system, in this case a car. Pick
five of the objects you listed and for each list several attributes and several
behaviors. Describe briefly how these objects interact with one another and
other objects in your description. You have just performed several of the key
steps in a typical object-oriented design.<br>
</page>
<page pagename="Exercise 2.65">
<b>Exercise 2.65</b><br>
<i>(Peter Minuet Problem)</i> Legend has it that in 1626 Peter Minuet purchased
Manhattan for $24.00 in barter. Did he make a good investment? To answer this
question, modify the compound interest program of<a href="^Code::c:s0p7"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 2.21</a> to begin with a
principal of $24.00 and to calculate the amount of interest on deposit if that
money had been kept on deposit until this year (372 years through 1998). Run
the program with interest rates of 5%, 6%, 7%, 8%, 9% and 10% to observe the